@etilic/rutter_ai 0.0.0-stage → 0.2.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.
Files changed (66) hide show
  1. package/LICENSE +27 -0
  2. package/README.md +80 -2
  3. package/THIRD_PARTY_LICENSES.txt +111 -0
  4. package/bin/cli.cjs +94 -0
  5. package/bin/npm-runtime.cjs +125 -0
  6. package/client/darwin-arm64/bootstrap.cjs +159 -0
  7. package/client/darwin-arm64/compat.cjs +61 -0
  8. package/client/darwin-arm64/hook.cjs +597 -0
  9. package/client/darwin-arm64/install.cjs +555 -0
  10. package/client/darwin-arm64/manifest.json +1 -0
  11. package/client/darwin-arm64/mcp.cjs +5666 -0
  12. package/client/darwin-arm64/migration.cjs +53 -0
  13. package/client/darwin-arm64/node_sqlite3.node +0 -0
  14. package/client/darwin-arm64/ordered-upload.cjs +236 -0
  15. package/client/darwin-arm64/outbox.cjs +218 -0
  16. package/client/darwin-arm64/recovery.cjs +61 -0
  17. package/client/darwin-arm64/sqlite3.cjs +217 -0
  18. package/client/darwin-arm64/transcript.cjs +138 -0
  19. package/client/darwin-arm64/upload.cjs +446 -0
  20. package/client/darwin-arm64/worker.cjs +76 -0
  21. package/client/darwin-x64/bootstrap.cjs +159 -0
  22. package/client/darwin-x64/compat.cjs +61 -0
  23. package/client/darwin-x64/hook.cjs +597 -0
  24. package/client/darwin-x64/install.cjs +555 -0
  25. package/client/darwin-x64/manifest.json +1 -0
  26. package/client/darwin-x64/mcp.cjs +5666 -0
  27. package/client/darwin-x64/migration.cjs +53 -0
  28. package/client/darwin-x64/node_sqlite3.node +0 -0
  29. package/client/darwin-x64/ordered-upload.cjs +236 -0
  30. package/client/darwin-x64/outbox.cjs +218 -0
  31. package/client/darwin-x64/recovery.cjs +61 -0
  32. package/client/darwin-x64/sqlite3.cjs +217 -0
  33. package/client/darwin-x64/transcript.cjs +138 -0
  34. package/client/darwin-x64/upload.cjs +446 -0
  35. package/client/darwin-x64/worker.cjs +76 -0
  36. package/client/linux-x64-glibc/bootstrap.cjs +159 -0
  37. package/client/linux-x64-glibc/compat.cjs +61 -0
  38. package/client/linux-x64-glibc/hook.cjs +597 -0
  39. package/client/linux-x64-glibc/install.cjs +555 -0
  40. package/client/linux-x64-glibc/manifest.json +1 -0
  41. package/client/linux-x64-glibc/mcp.cjs +5666 -0
  42. package/client/linux-x64-glibc/migration.cjs +53 -0
  43. package/client/linux-x64-glibc/node_sqlite3.node +0 -0
  44. package/client/linux-x64-glibc/ordered-upload.cjs +236 -0
  45. package/client/linux-x64-glibc/outbox.cjs +218 -0
  46. package/client/linux-x64-glibc/recovery.cjs +61 -0
  47. package/client/linux-x64-glibc/sqlite3.cjs +217 -0
  48. package/client/linux-x64-glibc/transcript.cjs +138 -0
  49. package/client/linux-x64-glibc/upload.cjs +446 -0
  50. package/client/linux-x64-glibc/worker.cjs +76 -0
  51. package/client/win32-x64/bootstrap.cjs +159 -0
  52. package/client/win32-x64/compat.cjs +61 -0
  53. package/client/win32-x64/hook.cjs +597 -0
  54. package/client/win32-x64/install.cjs +555 -0
  55. package/client/win32-x64/manifest.json +1 -0
  56. package/client/win32-x64/mcp.cjs +5666 -0
  57. package/client/win32-x64/migration.cjs +53 -0
  58. package/client/win32-x64/node_sqlite3.node +0 -0
  59. package/client/win32-x64/ordered-upload.cjs +236 -0
  60. package/client/win32-x64/outbox.cjs +218 -0
  61. package/client/win32-x64/recovery.cjs +61 -0
  62. package/client/win32-x64/sqlite3.cjs +217 -0
  63. package/client/win32-x64/transcript.cjs +138 -0
  64. package/client/win32-x64/upload.cjs +446 -0
  65. package/client/win32-x64/worker.cjs +76 -0
  66. package/package.json +34 -4
@@ -0,0 +1,597 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ const { request: fetch, performance } = require('./compat.cjs');
5
+
6
+ const crypto = require('node:crypto');
7
+ const fs = require('node:fs');
8
+ const http = require('node:http');
9
+ const os = require('node:os');
10
+ const path = require('node:path');
11
+ const { spawn } = require('node:child_process');
12
+
13
+ const MAX_HOOK_INPUT = 1024 * 1024;
14
+ const MAX_GATE_BODY = 32 * 1024;
15
+ const GATE_TIMEOUT_MS = 5 * 60 * 1000;
16
+ const MAX_DISPLAY = 240;
17
+ const MAX_DIAGNOSTIC_BYTES = 256 * 1024;
18
+
19
+ function diagnosticFile(env = process.env) {
20
+ return path.join(env.HOME || os.homedir(), '.config', 'rutter-direct-memory', 'diagnostics.jsonl');
21
+ }
22
+
23
+ // Only fixed vocabulary and numeric metrics cross this boundary. Never serialize
24
+ // errors, events, URLs, paths, selections, prompts, credentials or responses.
25
+ function diagnostic(env, stage, result, metrics = {}) {
26
+ if (!['binding', 'gate', 'catalog', 'context', 'capture', 'queue', 'upload', 'lock'].includes(stage)
27
+ || !['reused', 'missing', 'off', 'opened', 'ok', 'failed', 'incomplete', 'queued', 'acknowledged', 'revoked', 'identity_changed', 'skipped', 'full', 'capture_blocked'].includes(result)) return;
28
+ try {
29
+ const row = { time: new Date().toISOString(), stage, result };
30
+ if (['timeout', 'network', 'invalid_response', 'rejected', 'unconfirmed', 'local_state', 'source_or_storage', 'capability', 'consent', 'identity'].includes(metrics.reason)) row.reason = metrics.reason;
31
+ if (typeof metrics.id === 'string' && metrics.id) row.id = crypto.createHash('sha256').update(metrics.id).digest('hex').slice(0, 24);
32
+ for (const key of ['duration_ms', 'count', 'pending', 'status', 'age_ms']) {
33
+ if (Number.isFinite(metrics[key]) && metrics[key] >= 0) row[key] = Math.round(metrics[key] * 1000) / 1000;
34
+ }
35
+ const file = diagnosticFile(env);
36
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
37
+ // open(O_NOFOLLOW) prevents a log symlink from redirecting writes.
38
+ const fd = fs.openSync(file, fs.constants.O_WRONLY | fs.constants.O_APPEND | fs.constants.O_CREAT | (fs.constants.O_NOFOLLOW || 0), 0o600);
39
+ try {
40
+ fs.fchmodSync(fd, 0o600);
41
+ if (fs.fstatSync(fd).size >= MAX_DIAGNOSTIC_BYTES) {
42
+ const backup = `${file}.1`;
43
+ const temp = `${backup}.${process.pid}.${crypto.randomBytes(6).toString('hex')}.tmp`;
44
+ try {
45
+ fs.copyFileSync(file, temp, fs.constants.COPYFILE_EXCL);
46
+ fs.chmodSync(temp, 0o600);
47
+ fs.renameSync(temp, backup);
48
+ } finally { fs.rmSync(temp, { force: true }); }
49
+ fs.ftruncateSync(fd, 0);
50
+ }
51
+ fs.writeSync(fd, JSON.stringify(row) + '\n');
52
+ } finally { fs.closeSync(fd); }
53
+ } catch { /* Diagnostics must not prevent selection or uploading. */ }
54
+ }
55
+
56
+ function canonicalDirectory(directory) {
57
+ if (typeof directory !== 'string' || !directory) return '';
58
+ try { return fs.realpathSync.native(path.resolve(directory)); }
59
+ catch { return path.resolve(directory); }
60
+ }
61
+
62
+ class MemoryAccessError extends Error {
63
+ constructor(message, status = 503, reason) {
64
+ super(message);
65
+ this.name = 'MemoryAccessError';
66
+ this.status = status;
67
+ this.reason = reason;
68
+ }
69
+ }
70
+
71
+ function configPath(env = process.env) {
72
+ return env.RUTTER_DIRECT_MEMORY_CONFIG || path.join(env.HOME || os.homedir(), '.config', 'rutter-direct-memory', 'config.json');
73
+ }
74
+
75
+ function stateDirectory(env = process.env) {
76
+ return env.RUTTER_DIRECT_MEMORY_STATE_DIR || path.join(env.HOME || os.homedir(), '.config', 'rutter-direct-memory', 'sessions');
77
+ }
78
+
79
+ function readConfig(file = configPath()) {
80
+ let config;
81
+ try { config = JSON.parse(fs.readFileSync(file, 'utf8')); }
82
+ catch { throw new MemoryAccessError('Memory 接入尚未配置或本地配置无法读取。请先运行安装器完成配置。', 400); }
83
+ if (!config || typeof config !== 'object' || Array.isArray(config)
84
+ || typeof config.service_url !== 'string' || typeof config.service_id !== 'string'
85
+ || typeof config.memory_user_key !== 'string' || !config.memory_user_key) {
86
+ throw new MemoryAccessError('Memory 接入配置不完整。请运行安装器检查配置。', 400);
87
+ }
88
+ let url;
89
+ try { url = new URL(config.service_url); } catch { throw new MemoryAccessError('Memory 服务地址无效,请检查本地配置。', 400); }
90
+ const localHttp = ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname);
91
+ if (!['https:', ...(localHttp ? ['http:'] : [])].includes(url.protocol) || url.search || url.hash || !url.pathname.replace(/\/$/, '').endsWith('/v3')) {
92
+ throw new MemoryAccessError('Memory 服务地址必须是 HTTPS 的 /v3 API 地址。', 400);
93
+ }
94
+ if (!/^[A-Za-z0-9_-]{1,200}$/.test(config.service_id) || /[\r\n]/.test(config.memory_user_key)) {
95
+ throw new MemoryAccessError('Memory 接入配置格式无效,请运行安装器检查配置。', 400);
96
+ }
97
+ if (config.upload_concurrency !== undefined && (!Number.isInteger(config.upload_concurrency) || config.upload_concurrency < 1 || config.upload_concurrency > 10)) {
98
+ throw new MemoryAccessError('upload_concurrency 必须是 1–10 的整数。', 400);
99
+ }
100
+ return { service_url: url.toString().replace(/\/$/, ''), service_id: config.service_id, memory_user_key: config.memory_user_key,
101
+ ...(config.upload_concurrency === undefined ? {} : { upload_concurrency: config.upload_concurrency }) };
102
+ }
103
+
104
+ function configFingerprint(config) {
105
+ return crypto.createHash('sha256').update(JSON.stringify([config.service_url, config.service_id, config.memory_user_key])).digest('hex');
106
+ }
107
+
108
+ function defaultsFile(env = process.env) {
109
+ return path.join(path.dirname(configPath(env)), 'directory-defaults.json');
110
+ }
111
+
112
+ function readDirectoryDefaults(env = process.env) {
113
+ let data;
114
+ try { data = JSON.parse(fs.readFileSync(defaultsFile(env), 'utf8')); }
115
+ catch (error) {
116
+ if (error.code === 'ENOENT') return { version: 1, entries: [] };
117
+ throw new MemoryAccessError('目录默认配置无法读取;请检查本机 directory-defaults.json 后运行 config project set。', 400);
118
+ }
119
+ if (data?.version !== 1 || !Array.isArray(data.entries) || data.entries.some(entry => !entry || typeof entry.directory !== 'string'
120
+ || !path.isAbsolute(entry.directory) || !/^[a-f0-9]{64}$/.test(entry.fingerprint)
121
+ || !['team_id', 'company_id', 'project_id', 'agent_id'].every(key => typeof entry.selection?.[key] === 'string' && entry.selection[key])
122
+ || typeof entry.selection.task_id !== 'string' || typeof entry.selection.upload_enabled !== 'boolean')) {
123
+ throw new MemoryAccessError('目录默认配置格式无效;请检查本机 directory-defaults.json 后运行 config project set。', 400);
124
+ }
125
+ return data;
126
+ }
127
+
128
+ function directoryDefault(cwd, env = process.env) {
129
+ const current = canonicalDirectory(cwd);
130
+ return readDirectoryDefaults(env).entries.filter(entry => {
131
+ const relative = path.relative(entry.directory, current);
132
+ return !relative || (!path.isAbsolute(relative) && relative !== '..' && !relative.startsWith(`..${path.sep}`));
133
+ }).sort((a, b) => b.directory.length - a.directory.length)[0] || null;
134
+ }
135
+
136
+ function sessionFile(client, sessionId, env = process.env) {
137
+ const digest = crypto.createHash('sha256').update(`${client}\0${sessionId}`).digest('hex');
138
+ return path.join(stateDirectory(env), `${digest}.json`);
139
+ }
140
+
141
+ function readSession(client, sessionId, cwd, env = process.env) {
142
+ if (!sessionId || typeof sessionId !== 'string') return null;
143
+ try {
144
+ const state = JSON.parse(fs.readFileSync(sessionFile(client, sessionId, env), 'utf8'));
145
+ if (state?.client !== client || state?.session_id !== sessionId
146
+ || !state.cwd || !cwd || canonicalDirectory(state.cwd) !== canonicalDirectory(cwd)) return null;
147
+ if (state.mode === 'off') return state;
148
+ if (!['team_id', 'company_id', 'project_id', 'agent_id'].every(key => typeof state[key] === 'string' && state[key])
149
+ || typeof state.task_id !== 'string') return null;
150
+ return state;
151
+ } catch { return null; }
152
+ }
153
+
154
+ function writeSession(client, sessionId, cwd, selection, env = process.env) {
155
+ const directory = stateDirectory(env);
156
+ fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
157
+ fs.chmodSync(directory, 0o700);
158
+ const file = sessionFile(client, sessionId, env);
159
+ const temp = `${file}.${process.pid}.${crypto.randomBytes(5).toString('hex')}.tmp`;
160
+ const state = { client, session_id: sessionId, cwd: canonicalDirectory(cwd), ...selection, saved_at: new Date().toISOString() };
161
+ fs.writeFileSync(temp, `${JSON.stringify(state)}\n`, { mode: 0o600, flag: 'wx' });
162
+ fs.renameSync(temp, file);
163
+ fs.chmodSync(file, 0o600);
164
+ }
165
+
166
+ function publicError(error) {
167
+ if (error instanceof MemoryAccessError) return error.message.slice(0, MAX_DISPLAY);
168
+ if (error?.name === 'AbortError' || error?.name === 'TimeoutError') return '连接 Memory 服务超时。请检查网络后重试。';
169
+ return 'Memory 服务暂时不可用。请检查网络和服务状态后重试。';
170
+ }
171
+
172
+ async function requestMemory(config, endpoint, body, fetcher = fetch) {
173
+ let response;
174
+ try {
175
+ response = await fetcher(`${config.service_url}/hierarchy/direct-memory/${endpoint}`, {
176
+ method: 'POST', redirect: 'error', timeoutMs: 15000,
177
+ headers: { 'content-type': 'application/json', 'x-tdai-service-id': config.service_id, 'x-tdai-user-key': config.memory_user_key },
178
+ body: JSON.stringify(body),
179
+ });
180
+ } catch (error) {
181
+ if (error?.name === 'AbortError' || error?.name === 'TimeoutError') throw new MemoryAccessError('连接 Memory 服务超时。请检查网络后重试。', 503, 'timeout');
182
+ throw new MemoryAccessError('Memory 服务暂时不可用。请检查网络和服务状态后重试。', 503, 'network');
183
+ }
184
+ let envelope;
185
+ try { envelope = await response.json(); } catch { throw new MemoryAccessError('Memory 服务返回了无法识别的响应。请重试或取消。', 503, 'invalid_response'); }
186
+ if (!response.ok || envelope?.code !== 0 || !envelope.data || typeof envelope.data !== 'object') {
187
+ const status = response.status || envelope?.code;
188
+ const message = status === 401 ? 'Memory 用户凭证无效或已过期。请更新本地凭证后重试。'
189
+ : status === 403 ? '所选团队、Agent 或 Task 当前无权访问。请重试或取消。'
190
+ : status === 404 ? '所选项目或资产已不存在。请重新选择或取消。'
191
+ : status === 400 ? 'Memory 请求参数无效。请重试或取消。'
192
+ : 'Memory 服务暂时不可用。请检查网络和服务状态后重试。';
193
+ throw new MemoryAccessError(message, status || 503, 'rejected');
194
+ }
195
+ return envelope.data;
196
+ }
197
+
198
+ function escapeHtml(value) {
199
+ return String(value ?? '').replace(/[&<>"']/g, char => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[char]);
200
+ }
201
+
202
+ function safeJsonForHtml(value) {
203
+ return JSON.stringify(value).replace(/</g, '\\u003c').replace(/>/g, '\\u003e').replace(/&/g, '\\u0026');
204
+ }
205
+
206
+ function normalizeCatalog(data) {
207
+ if (!Array.isArray(data?.teams)) throw new MemoryAccessError('Memory 服务未返回有效的团队目录。请重试或取消。');
208
+ return data.teams.filter(team => typeof team?.team_id === 'string' && Array.isArray(team.projects) && Array.isArray(team.agents) && Array.isArray(team.tasks))
209
+ .map(team => ({
210
+ team_id: team.team_id, name: String(team.name || team.team_id),
211
+ projects: team.projects.filter(project => typeof project?.project_id === 'string' && typeof project.company_id === 'string')
212
+ .map(project => ({ company_id: project.company_id, project_id: project.project_id, name: String(project.name || project.project_id) })),
213
+ agents: team.agents.filter(agent => typeof agent?.agent_id === 'string')
214
+ .map(agent => ({ agent_id: agent.agent_id, name: String(agent.name || agent.agent_id), description: String(agent.description || '') })),
215
+ tasks: team.tasks.filter(task => typeof task?.task_id === 'string')
216
+ .map(task => ({ task_id: task.task_id, title: String(task.title || task.task_id), status: String(task.status || '') })),
217
+ }));
218
+ }
219
+
220
+ function validateSelection(catalog, selection) {
221
+ const team = catalog.find(item => item.team_id === selection.team_id);
222
+ const project = team?.projects.find(item => item.project_id === selection.project_id && item.company_id === selection.company_id);
223
+ const agent = team?.agents.find(item => item.agent_id === selection.agent_id);
224
+ const taskId = selection.task_id || '';
225
+ const task = taskId ? team?.tasks.find(item => item.task_id === taskId) : null;
226
+ if (!team || !project || !agent || (taskId && !task)) throw new MemoryAccessError('请选择同一团队中有效的项目和 Agent;Task 可留空。', 400);
227
+ return { team_id: team.team_id, company_id: project.company_id, project_id: project.project_id, agent_id: agent.agent_id, task_id: taskId, upload_enabled: selection.upload_enabled === true };
228
+ }
229
+
230
+ function renderPage(catalog, token, uploadDisabled = false, expiresAt = Date.now() + GATE_TIMEOUT_MS) {
231
+ const serialized = safeJsonForHtml(catalog);
232
+ return `<!doctype html><html lang="zh-CN"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; connect-src 'self'"><title>Memory 接入</title><style>body{font:16px system-ui,sans-serif;max-width:680px;margin:4rem auto;padding:0 1rem;color:#202124}label{display:block;margin:1rem 0}select,button{font:inherit;padding:.5rem;max-width:100%}select{display:block;width:100%;margin-top:.3rem}button{margin:.5rem .5rem .5rem 0}#error{color:#9b1c1c}#status{color:#555}.choice{display:flex;gap:.5rem;align-items:center}.choice input{width:1rem;height:1rem}</style><h1>选择本次对话使用的 Memory 资产</h1><p>模型 API Key 不会发送给 Memory 服务。</p><form id="choose"><label>团队<select id="team" required></select></label><label>项目<select id="project" required></select></label><label>Agent<select id="agent" required></select></label><label>Task(可选)<select id="task"></select></label><label class="choice"><input id="upload" type="checkbox"${uploadDisabled ? ' disabled' : ' checked'}>上传本会话的用户文本和最终助手回复到项目 L0</label>${uploadDisabled ? '<p>上传已全局关闭。请检查 Memory 地址和凭证后,重新运行安装命令恢复上传,再开启新会话。</p>' : ''}<button>确认选择并加载上下文</button><button type="button" data-action="skip">本次不使用 Memory</button></form><section id="failure" hidden><p id="error"></p><button data-action="retry">重试</button><button data-action="reselect">重新选择资产</button><button data-action="continue">仅本次无 Memory 上下文继续</button><button data-action="skip">本次不使用 Memory</button><button data-action="cancel">取消本次请求</button></section><p id="status" aria-live="polite"></p><script>
233
+ let catalog=${serialized};const token=${JSON.stringify(token)};const root='/'+token;const expiresAt=${JSON.stringify(expiresAt)};let terminal=false,submitting=false;const team=document.querySelector('#team'),project=document.querySelector('#project'),agent=document.querySelector('#agent'),task=document.querySelector('#task'),choose=document.querySelector('#choose'),failure=document.querySelector('#failure'),error=document.querySelector('#error'),status=document.querySelector('#status');
234
+ function options(el,items,id,label,placeholder,optional=false){const selected=el.value;const first=document.createElement('option');first.value='';first.textContent=placeholder;first.disabled=!optional;el.replaceChildren(first,...items.map(x=>{const o=document.createElement('option');o.value=x[id];o.textContent=x[label];return o}));if([...el.options].some(o=>o.value===selected))el.value=selected;else el.value=''}function selectedTeam(){return catalog.find(x=>x.team_id===team.value)}function refresh(){const t=selectedTeam();options(project,t?.projects||[],'project_id','name',t&&!(t.projects||[]).length?'暂无已授权项目,请联系管理员确认':'请选择项目');options(agent,t?.agents||[],'agent_id','name','请选择 Agent');options(task,t?.tasks||[],'task_id','title','不关联 Task',true)}function setCatalog(value){catalog=value;options(team,catalog,'team_id','name','请选择团队');refresh()}setCatalog(catalog);team.addEventListener('change',()=>{project.value='';agent.value='';task.value='';refresh()});
235
+ async function request(endpoint,body){const controller=new AbortController();const timer=setTimeout(()=>controller.abort(),3000);try{const r=await fetch(root+endpoint,{method:body?'POST':'GET',cache:'no-store',signal:controller.signal,headers:body?{'content-type':'application/json'}:undefined,body:body?JSON.stringify(body):undefined});if(!r.ok)throw new Error('request failed');return await r.json()}finally{clearTimeout(timer)}}
236
+ choose.addEventListener('submit',async e=>{e.preventDefault();if(submitting||terminal)return;submitting=true;status.textContent='正在读取授权上下文…';const t=selectedTeam(),p=t?.projects.find(x=>x.project_id===project.value);try{await request('/selection',{team_id:team.value,company_id:p?.company_id,project_id:project.value,agent_id:agent.value,task_id:task.value,upload_enabled:document.querySelector('#upload').checked});choose.hidden=true;status.textContent='已提交选择,正在加载上下文…'}catch{status.textContent='未能确认选择是否提交,请等待状态更新或刷新页面重试。'}finally{submitting=false}});
237
+ document.querySelectorAll('[data-action]').forEach(b=>b.addEventListener('click',async()=>{if(submitting||terminal)return;submitting=true;try{await request('/action',{action:b.dataset.action});failure.hidden=true;choose.hidden=true;status.textContent=b.dataset.action==='reselect'?'已打开新的资产选择页面,可以关闭此页面':b.dataset.action==='retry'?'正在重试…':b.dataset.action==='continue'?'正在继续本次请求…':b.dataset.action==='skip'?'本次会话已关闭 Memory,可以关闭此页面':'请求已取消,可以关闭此页面';if(['continue','skip','cancel','reselect'].includes(b.dataset.action))terminal=true}catch{status.textContent='操作未确认,请刷新页面重试。'}finally{submitting=false}}));
238
+ async function poll(){if(terminal)return;try{const s=await request('/status');if(s.mode==='error'){failure.hidden=false;choose.hidden=true;error.textContent=s.error;document.querySelector('[data-action="continue"]').hidden=s.allow_continue===false;status.textContent='上下文加载失败,请明确选择下一步'}else if(s.mode==='select'){if(Array.isArray(s.catalog))setCatalog(s.catalog);failure.hidden=true;choose.hidden=false}else if(s.mode==='loading'){failure.hidden=true;choose.hidden=true;status.textContent='正在加载…'}else if(['done','off','continued','cancelled'].includes(s.mode)){terminal=true;failure.hidden=true;choose.hidden=true;status.textContent=s.message||(s.mode==='done'?'上下文已加载完成,可以关闭此页面并返回 AI 客户端':s.mode==='cancelled'?'已取消,可以关闭此页面':'本次未加载 Memory 上下文,可以关闭此页面')}}catch{if(Date.now()>=expiresAt){terminal=true;choose.hidden=true;failure.hidden=true;status.textContent='等待选择超时,本次请求已取消,可以关闭此页面'}else status.textContent='状态连接已中断,尚未确认上下文加载成功。正在重试;也可以刷新页面。'}if(!terminal)setTimeout(poll,500)}poll();</script></html>`;
239
+ }
240
+
241
+ function createGate({ catalog = [], initialError = null, allowContinue = true, uploadDisabled = false, timeoutMs = GATE_TIMEOUT_MS } = {}) {
242
+ const token = crypto.randomBytes(32).toString('hex');
243
+ let pageCatalog = catalog;
244
+ let state = { mode: initialError ? 'error' : 'select', error: initialError || '', allowContinue };
245
+ let resolveSelection;
246
+ let resolveAction;
247
+ let selectionSettled = false;
248
+ let actionPending = null;
249
+ let earlyAction = null;
250
+ let expired = false;
251
+ let server;
252
+ let timer;
253
+ let expiresAt;
254
+ let delivered = false;
255
+ let resolveTerminal;
256
+ const terminalStatus = new Promise(resolve => { resolveTerminal = resolve; });
257
+ const isTerminal = () => ['done', 'off', 'continued', 'cancelled'].includes(state.mode);
258
+ const selection = new Promise(resolve => { resolveSelection = resolve; });
259
+ const action = () => new Promise(resolve => { actionPending = resolve; });
260
+ const setState = next => { state = { ...next }; };
261
+ function json(res, code, body) {
262
+ res.writeHead(code, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store', 'x-content-type-options': 'nosniff' });
263
+ res.end(JSON.stringify(body));
264
+ }
265
+ function readBody(req) {
266
+ return new Promise((resolve, reject) => {
267
+ let body = '';
268
+ req.on('data', chunk => {
269
+ body += chunk;
270
+ if (Buffer.byteLength(body) > MAX_GATE_BODY) { reject(new Error('request too large')); req.destroy(); }
271
+ });
272
+ req.on('end', () => { try { resolve(JSON.parse(body)); } catch { reject(new Error('invalid JSON')); } });
273
+ req.on('error', reject);
274
+ });
275
+ }
276
+ server = http.createServer(async (req, res) => {
277
+ const remote = req.socket.remoteAddress;
278
+ if (!['127.0.0.1', '::1', '::ffff:127.0.0.1'].includes(remote)) return json(res, 403, { error: 'loopback only' });
279
+ const url = new URL(req.url, 'http://127.0.0.1');
280
+ const base = `/${token}`;
281
+ res.setHeader('cache-control', 'no-store');
282
+ res.setHeader('x-content-type-options', 'nosniff');
283
+ if (req.method === 'GET' && url.pathname === base) {
284
+ res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; connect-src 'self'" });
285
+ return res.end(renderPage(pageCatalog, token, uploadDisabled, expiresAt));
286
+ }
287
+ if (req.method === 'GET' && url.pathname === `${base}/status`) {
288
+ if (isTerminal()) res.once('finish', () => { delivered = true; resolveTerminal(true); });
289
+ return json(res, 200, {
290
+ mode: state.mode, error: state.error, message: state.message, allow_continue: state.allowContinue !== false,
291
+ ...(state.mode === 'select' ? { catalog: pageCatalog } : {}),
292
+ });
293
+ }
294
+ if (req.method !== 'POST' || ![`${base}/selection`, `${base}/action`].includes(url.pathname)) return json(res, 404, { error: 'not found' });
295
+ let body;
296
+ try { body = await readBody(req); } catch { return json(res, 400, { error: 'invalid request' }); }
297
+ if (url.pathname === `${base}/selection`) {
298
+ if (state.mode !== 'select' || selectionSettled) return json(res, 409, { error: 'selection is not available' });
299
+ if (uploadDisabled && body?.upload_enabled === true) return json(res, 400, { error: 'upload is globally disabled' });
300
+ try {
301
+ const selected = validateSelection(catalog, body);
302
+ selectionSettled = true;
303
+ setState({ mode: 'loading' });
304
+ resolveSelection(selected);
305
+ return json(res, 202, { accepted: true });
306
+ } catch (error) { return json(res, 400, { error: publicError(error) }); }
307
+ }
308
+ const actions = { reselect: 'reselect', retry: 'retry', continue: 'continue', cancel: 'cancel', skip: 'skip' };
309
+ const selectedAction = actions[body?.action];
310
+ if (!['error', 'select'].includes(state.mode) || !selectedAction || (state.mode === 'select' && selectedAction !== 'skip') || (selectedAction === 'continue' && state.allowContinue === false)) return json(res, 409, { error: 'action is not available' });
311
+ if (selectedAction === 'skip' && !selectionSettled) { selectionSettled = true; resolveSelection({ mode: 'off' }); }
312
+ if (selectedAction === 'retry') setState({ mode: 'loading' });
313
+ else setState({ mode: selectedAction === 'cancel' ? 'cancelled' : selectedAction === 'skip' ? 'off' : selectedAction === 'reselect' ? 'reselect' : 'continued', message: selectedAction === 'cancel' ? '' : selectedAction === 'skip' ? '本次会话已关闭 Memory' : '已选择仅本次无 Memory 上下文继续' });
314
+ if (actionPending) {
315
+ const resolve = actionPending;
316
+ actionPending = null;
317
+ resolve(selectedAction);
318
+ } else earlyAction = selectedAction;
319
+ return json(res, 202, { accepted: true });
320
+ });
321
+ return {
322
+ get url() { const address = server.address(); return address ? `http://127.0.0.1:${address.port}/${token}` : ''; },
323
+ async start() {
324
+ await new Promise((resolve, reject) => { server.once('error', reject); server.listen(0, '127.0.0.1', resolve); });
325
+ expiresAt = Date.now() + timeoutMs;
326
+ timer = setTimeout(() => {
327
+ expired = true;
328
+ if (actionPending) { const resolve = actionPending; actionPending = null; resolve('cancel'); }
329
+ if (!selectionSettled) { selectionSettled = true; resolveSelection(null); }
330
+ setState({ mode: 'cancelled', message: '等待选择超时,本次请求已取消。' });
331
+ this.close();
332
+ }, timeoutMs);
333
+ timer.unref?.();
334
+ return this;
335
+ },
336
+ waitForSelection: () => selection,
337
+ showSelection(nextCatalog) { pageCatalog = nextCatalog; setState({ mode: 'select' }); },
338
+ showError(message, options = {}) { setState({ mode: 'error', error: String(message).slice(0, MAX_DISPLAY), allowContinue: options.allowContinue ?? allowContinue }); },
339
+ setDone(message = '上下文已加载完成,可以关闭此页面并返回 AI 客户端') { setState({ mode: 'done', message }); },
340
+ async waitForTerminal(timeoutMs = 1500) {
341
+ if (delivered || !isTerminal()) return;
342
+ let deadline;
343
+ try { await Promise.race([terminalStatus, new Promise(resolve => { deadline = setTimeout(resolve, timeoutMs); })]); }
344
+ finally { clearTimeout(deadline); }
345
+ },
346
+ async waitForAction() {
347
+ if (expired) return 'cancel';
348
+ if (earlyAction) { const value = earlyAction; earlyAction = null; return value; }
349
+ return action();
350
+ },
351
+ close() {
352
+ clearTimeout(timer);
353
+ resolveTerminal(false);
354
+ if (!server.listening) return;
355
+ server.close();
356
+ // A stalled browser request must not keep the hook process alive.
357
+ const drain = setTimeout(() => server.closeAllConnections(), 100);
358
+ drain.unref?.();
359
+ },
360
+ };
361
+ }
362
+
363
+ function openGate(url, stderr = process.stderr) {
364
+ const platform = process.platform;
365
+ const command = platform === 'darwin' ? 'open' : platform === 'win32' ? 'cmd.exe' : 'xdg-open';
366
+ const args = platform === 'win32' ? ['/c', 'start', '', url] : [url];
367
+ try {
368
+ const child = spawn(command, args, { detached: true, stdio: 'ignore', windowsHide: true });
369
+ child.on('error', () => stderr.write(`请在浏览器打开本机选择页面:${url}\n`));
370
+ child.unref();
371
+ } catch { stderr.write(`请在浏览器打开本机选择页面:${url}\n`); }
372
+ }
373
+
374
+ function formatContext(context) {
375
+ const lines = ['<memory-context>', `Team: ${context.team?.name || context.team?.team_id || ''}`, `Project: ${context.project?.name || context.project?.project_id || ''}`];
376
+ if (context.agent?.prompt) lines.push(`\nAgent instructions:\n${context.agent.prompt}`);
377
+ if (context.task?.title || context.task?.description) lines.push(`\nTask:\n${[context.task.title, context.task.description].filter(Boolean).join('\n')}`);
378
+ lines.push('\nProject and team knowledge:');
379
+ if (Array.isArray(context.knowledge) && context.knowledge.length) {
380
+ for (const item of context.knowledge) lines.push(`- [${item.type || 'knowledge'}] ${item.name || ''}: ${item.summary || ''}`);
381
+ } else lines.push('- No authorized knowledge items are available.');
382
+ lines.push('\nRelevant authorized memories:');
383
+ if (Array.isArray(context.memories) && context.memories.length) {
384
+ for (const item of context.memories) lines.push(`- ${item.content || ''}`);
385
+ } else lines.push('- No relevant authorized memories were found.');
386
+ lines.push('</memory-context>');
387
+ return lines.join('\n');
388
+ }
389
+
390
+ function hookResult(client, context, blockedMessage = '') {
391
+ if (blockedMessage) return client === 'claude'
392
+ ? { decision: 'block', reason: blockedMessage }
393
+ : { continue: false, stopReason: blockedMessage };
394
+ if (!context) return {};
395
+ return { hookSpecificOutput: { hookEventName: 'UserPromptSubmit', additionalContext: formatContext(context) } };
396
+ }
397
+
398
+ async function runHook({ client, event, env = process.env, fetcher = fetch, gateFactory = createGate, browser = openGate, stderr = process.stderr }) {
399
+ if (!['codex', 'claude'].includes(client)) throw new MemoryAccessError('不支持的客户端。');
400
+ if (!event || event.hook_event_name !== 'UserPromptSubmit') return {};
401
+ const sessionId = event.session_id;
402
+ const cwd = typeof event.cwd === 'string' && event.cwd ? path.resolve(event.cwd) : '';
403
+ const prompt = typeof event.prompt === 'string' ? event.prompt : '';
404
+ if (!sessionId || !cwd || !prompt.trim()) throw new MemoryAccessError('客户端未提供稳定会话、工作目录或提示信息。为避免错绑项目,本次请求已阻止。', 400);
405
+
406
+ let saved = readSession(client, sessionId, cwd, env);
407
+ diagnostic(env, 'binding', saved?.mode === 'off' ? 'off' : saved ? 'reused' : 'missing', { id: `${client}:${sessionId}` });
408
+ if (saved?.mode === 'off') return {};
409
+ const config = readConfig(configPath(env));
410
+ const fingerprint = configFingerprint(config);
411
+ if (saved?.config_fingerprint && saved.config_fingerprint !== fingerprint) {
412
+ return hookResult(client, null, 'Memory 身份已改变,原会话和待传内容已保留。请用 config key 恢复原 Key,或开启新会话。');
413
+ }
414
+ const preset = saved ? null : directoryDefault(cwd, env);
415
+ if (preset && fs.existsSync(sessionFile(client, sessionId, env))) {
416
+ return hookResult(client, null, '已有会话的工作目录或状态已改变;原绑定保留,目录默认配置只用于新会话。请恢复原目录或开启新会话。');
417
+ }
418
+ if (preset && preset.fingerprint !== fingerprint) {
419
+ return hookResult(client, null, '目录默认项目属于原 Memory 身份。本次请求已阻止;请运行 config project set 重新配置,或用 config key 恢复原 Key。');
420
+ }
421
+ const defaultSource = saved?.default_source || preset?.directory;
422
+ let selection = saved && { team_id: saved.team_id, company_id: saved.company_id, project_id: saved.project_id, agent_id: saved.agent_id, task_id: saved.task_id, upload_enabled: saved.upload_enabled === true };
423
+ const uploadState = require('./upload.cjs').readState(env);
424
+ const expiredConsent = saved?.upload_enabled_at && saved.upload_enabled_at < uploadState.since;
425
+ if (expiredConsent) selection = null;
426
+ if (preset) selection = { ...preset.selection };
427
+ if (defaultSource && require('./upload.cjs').readState(env).manually_disabled) selection.upload_enabled = false;
428
+ let catalog = [];
429
+ let gate = null;
430
+ async function startGate(options) {
431
+ const uploadDisabled = require('./upload.cjs').readState(env).manually_disabled === true;
432
+ gate = await gateFactory({ ...options, uploadDisabled }).start();
433
+ diagnostic(env, 'gate', 'opened', { id: `${client}:${sessionId}` });
434
+ browser(gate.url, stderr);
435
+ return gate;
436
+ }
437
+ async function readCatalog() {
438
+ const started = performance.now();
439
+ try {
440
+ const result = normalizeCatalog(await requestMemory(config, 'catalog', {}, fetcher));
441
+ diagnostic(env, 'catalog', 'ok', { duration_ms: performance.now() - started, id: `${client}:${sessionId}` });
442
+ return result;
443
+ } catch (error) {
444
+ diagnostic(env, 'catalog', 'failed', { duration_ms: performance.now() - started, status: error.status, reason: error.reason, id: `${client}:${sessionId}` });
445
+ throw error;
446
+ }
447
+ }
448
+ try {
449
+ if (!selection) {
450
+ let catalogError = null;
451
+ for (;;) {
452
+ try { catalog = await readCatalog(); catalogError = catalog.some(team => team.projects.length && team.agents.length) ? null : '当前账号没有可选择的团队、项目或 Agent。请更新授权资产后重试。'; }
453
+ catch (error) { catalogError = publicError(error); }
454
+ if (!catalogError) break;
455
+ if (!gate) await startGate({ catalog: [], initialError: catalogError, allowContinue: false });
456
+ else gate.showError(catalogError, { allowContinue: false });
457
+ const decision = await gate.waitForAction();
458
+ if (decision === 'cancel' || !decision) return hookResult(client, null, 'Memory 资产选择未完成,本次请求已取消。');
459
+ if (decision === 'skip') { writeSession(client, sessionId, cwd, { mode: 'off' }, env); return {}; }
460
+ if (decision === 'continue') return hookResult(client, null);
461
+ }
462
+ if (!gate) await startGate({ catalog });
463
+ else gate.showSelection(catalog);
464
+ selection = await gate.waitForSelection();
465
+ if (!selection) return hookResult(client, null, 'Memory 资产选择等待超时,本次请求已取消。');
466
+ if (selection.mode === 'off') { writeSession(client, sessionId, cwd, { mode: 'off' }, env); return {}; }
467
+ writeSession(client, sessionId, cwd, { ...selection, config_fingerprint: fingerprint }, env);
468
+ }
469
+
470
+ for (;;) {
471
+ const started = performance.now();
472
+ try {
473
+ const context = await requestMemory(config, 'context', { ...selection, session_id: sessionId, query: prompt }, fetcher);
474
+ if (!Array.isArray(context.knowledge) || !Array.isArray(context.memories)
475
+ || !context.agent || typeof context.agent.prompt !== 'string'
476
+ || (context.task !== null && (!context.task || typeof context.task.title !== 'string'))) throw new MemoryAccessError('Memory 服务未返回完整上下文。请重试或取消。');
477
+ if (saved?.conversation_upload?.user_id && context.conversation_upload?.user_id
478
+ && saved.conversation_upload.user_id !== context.conversation_upload.user_id) {
479
+ if (!gate) await startGate({ catalog: await readCatalog() });
480
+ else gate.showSelection(await readCatalog());
481
+ selection = await gate.waitForSelection();
482
+ if (!selection) return hookResult(client, null, 'Memory 身份已改变,需要重新确认上传授权。');
483
+ if (selection.mode === 'off') { writeSession(client, sessionId, cwd, { mode: 'off' }, env); return {}; }
484
+ saved = null;
485
+ writeSession(client, sessionId, cwd, selection, env);
486
+ continue;
487
+ }
488
+ if ((selection.upload_enabled || saved?.upload_enabled_at)
489
+ && (context.conversation_upload?.protocol !== 'ordered-v1' || !context.conversation_upload.user_id)) {
490
+ throw new MemoryAccessError('Memory 服务尚未支持 ordered-v1 有序上传。请先升级服务器;原待传数据已保留。', 409, 'capability');
491
+ }
492
+ if (configFingerprint(readConfig(configPath(env))) !== fingerprint) throw new MemoryAccessError('Memory 配置在加载期间改变,本次请求已阻止。');
493
+ if (defaultSource && !(typeof context.session_binding === 'string' && /^[a-f0-9]{64}$/.test(context.session_binding))) throw new MemoryAccessError('Memory 服务未返回有效会话绑定。');
494
+ if (typeof context.session_binding === 'string' && /^[a-f0-9]{64}$/.test(context.session_binding)) {
495
+ let uploadEnabledAt = expiredConsent ? 0 : saved?.upload_enabled_at || 0;
496
+ let initialEventId = expiredConsent ? undefined : saved?.upload_initial_event_id;
497
+ let initialPrompt = expiredConsent ? undefined : saved?.upload_initial_prompt;
498
+ if (selection.upload_enabled && !uploadEnabledAt) {
499
+ uploadEnabledAt = await require('./upload.cjs').enableForSession(env);
500
+ // Claude writes the current prompt before UserPromptSubmit opens
501
+ // consent. Authorize that exact retained message, without moving
502
+ // the time boundary backwards over earlier conversation history.
503
+ if (typeof event.transcript_path === 'string' && path.isAbsolute(event.transcript_path)) {
504
+ let fd;
505
+ try {
506
+ fd = fs.openSync(event.transcript_path, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0));
507
+ const stat = fs.fstatSync(fd);
508
+ if (stat.isFile() && stat.size <= 32 * 1024 * 1024) {
509
+ const parsed = require('./transcript.cjs').parseOrderedTranscript(client, sessionId, fs.readFileSync(fd, 'utf8'));
510
+ const last = parsed.messages[parsed.messages.length - 1];
511
+ if (!parsed.incomplete && last?.role === 'user' && last.content === prompt) initialEventId = last.direct_event_id;
512
+ else if (!parsed.incomplete) initialPrompt = { hash: crypto.createHash('sha256').update(prompt).digest('hex'), after_bytes: stat.size };
513
+ }
514
+ } catch (error) {
515
+ // Some clients allocate the transcript path at the hook, then
516
+ // persist this prompt with its original timestamp afterwards.
517
+ if (error.code === 'ENOENT') initialPrompt = { hash: crypto.createHash('sha256').update(prompt).digest('hex'), after_bytes: 0 };
518
+ }
519
+ finally { if (fd !== undefined) fs.closeSync(fd); }
520
+ }
521
+ }
522
+ const next = { ...selection, config_fingerprint: fingerprint, ...(defaultSource ? { default_source: defaultSource } : {}), upload_config_fingerprint: require('./ordered-upload.cjs').fingerprint(config), session_binding: context.session_binding, upload_enabled_at: uploadEnabledAt,
523
+ ...(initialEventId ? { upload_initial_event_id: initialEventId } : {}),
524
+ ...(initialPrompt ? { upload_initial_prompt: initialPrompt } : {}),
525
+ ...(context.conversation_upload?.protocol === 'ordered-v1' ? { conversation_upload: context.conversation_upload } : {}) };
526
+ writeSession(client, sessionId, cwd, next, env);
527
+ if (uploadEnabledAt && context.conversation_upload?.protocol === 'ordered-v1') {
528
+ await require('./ordered-upload.cjs').register({ ...next, client, session_id: sessionId, cwd }, event, config, env);
529
+ }
530
+ }
531
+ gate?.setDone();
532
+ diagnostic(env, 'context', 'ok', { duration_ms: performance.now() - started, id: `${client}:${sessionId}` });
533
+ return hookResult(client, context);
534
+ } catch (error) {
535
+ if (!defaultSource && [403, 404].includes(error.status)) fs.rmSync(sessionFile(client, sessionId, env), { force: true });
536
+ diagnostic(env, 'context', 'failed', { duration_ms: performance.now() - started, status: error.status, reason: error.reason, id: `${client}:${sessionId}` });
537
+ if (defaultSource) return hookResult(client, null, `${publicError(error)} Memory 加载已停止;请运行 config project set 重新配置,或检查 config key。`);
538
+ if (!gate) await startGate({ catalog: [], initialError: publicError(error) });
539
+ else gate.showError(publicError(error));
540
+ const decision = await gate.waitForAction();
541
+ if (decision === 'reselect') {
542
+ fs.rmSync(sessionFile(client, sessionId, env), { force: true });
543
+ gate.close();
544
+ return runHook({ client, event, env, fetcher, gateFactory, browser, stderr });
545
+ }
546
+ if (decision === 'retry') continue;
547
+ if (decision === 'skip') { writeSession(client, sessionId, cwd, { mode: 'off' }, env); return {}; }
548
+ if (decision === 'continue') return hookResult(client, null);
549
+ return hookResult(client, null, 'Memory 上下文未加载,本次请求已取消。');
550
+ }
551
+ }
552
+ } finally {
553
+ try { await gate?.waitForTerminal?.(); } finally { gate?.close(); }
554
+ }
555
+ }
556
+
557
+ function parseClient(args) {
558
+ const index = args.indexOf('--client');
559
+ if (index >= 0) return args[index + 1];
560
+ const value = args.find(item => item.startsWith('--client='));
561
+ return value?.slice('--client='.length);
562
+ }
563
+
564
+ async function main() {
565
+ const chunks = [];
566
+ let size = 0;
567
+ for await (const chunk of process.stdin) {
568
+ size += chunk.length;
569
+ if (size > MAX_HOOK_INPUT) throw new MemoryAccessError('Hook 输入过大,本次请求已阻止。', 400);
570
+ chunks.push(chunk);
571
+ }
572
+ const event = JSON.parse(Buffer.concat(chunks).toString('utf8'));
573
+ const client = parseClient(process.argv.slice(2));
574
+ if (event.hook_event_name === 'Stop') {
575
+ try {
576
+ const warning = await require('./upload.cjs').capture({ client, event });
577
+ if (warning) process.stderr.write(`${warning}\n`);
578
+ } catch { process.stderr.write('Memory 对话上传未完成,请检查本地上传状态。\n'); }
579
+ process.stdout.write('{}\n');
580
+ return;
581
+ }
582
+ const result = await runHook({ client, event });
583
+ process.stdout.write(`${JSON.stringify(result)}\n`);
584
+ }
585
+
586
+ if (require.main === module) {
587
+ main().catch(error => {
588
+ const client = parseClient(process.argv.slice(2));
589
+ process.stderr.write(`${publicError(error)}\n`);
590
+ process.stdout.write(`${JSON.stringify(hookResult(client, null, publicError(error)))}\n`);
591
+ process.exitCode = 0;
592
+ });
593
+ }
594
+
595
+ module.exports = { MemoryAccessError, configPath, stateDirectory, readConfig, sessionFile, readSession, writeSession,
596
+ requestMemory, normalizeCatalog, validateSelection, formatContext, hookResult, createGate, runHook, publicError,
597
+ diagnostic, diagnosticFile, configFingerprint, canonicalDirectory, defaultsFile, readDirectoryDefaults, directoryDefault };