Skip to content

armgit / Orkas

Public Imported from GitHub
0

Orkas is an open-source (MIT), local-first AI team for your desktop: a Commander turns your goal into to-dos and coordinates 16 built-in specialist agents plus Claude Code, Codex, OpenCode, OpenClaw and Hermes, with projects, scheduled automations and connectors. Free app for macOS & Windows; built-in models or your own keys.

22.6 KB
Raw Blame
const _shimLog = createLogger('ipc-shim');
const _IPC_ERROR_DEDUPE_MS = 60 * 1000;
const _IPC_ERROR_MAX_PER_SESSION = 50;
const _IPC_ERROR_MAX_KEYS = 100;
const _ipcErrorRecent = new Map();
let _ipcErrorSentCount = 0;
// ─── HTTP → IPC shim ─────────────────────────────────────────────────
// The original app was served over HTTP; every network call went through
// `apiFetch(url, options)` which wrapped `fetch`. In Electron we route the
// same calls through `window.orkas.invoke` (for request/response) or
// `.stream` (for SSE). The shim translates URL + method into an IPC channel
// + payload and returns a Response-like object so the rest of the file's
// 3000+ lines can stay unchanged.
//
// Auth is gone entirely — local IPC is trusted by construction, so
// password / X-Access-Password / access-denied UI all become no-ops.

// Route table. Each entry = [method, pathMatcher, channel, paramKeys?, opts?]
//   - pathMatcher: string (exact match) or RegExp (capture groups → paramKeys)
//   - channel: IPC channel name (or special objects: { fake }, { upload })
//   - paramKeys: names assigned to regex capture groups, merged into payload
//   - opts.stream: boolean (this call yields an SSE-style stream)
//   - opts.wrapAsUpdates: wrap the whole body under `updates` key
const _IPC_ROUTES = [
  ['POST', '/api/apps/data-impact-from-path', 'savedApps.dataImpactFromPath'],
  ['POST', '/api/apps/export-data-from-path', 'savedApps.exportDataFromPath'],
  ['POST', '/api/conversations/cleanup/preview', 'conversations.cleanup.preview'],
  ['POST', '/api/conversations/cleanup/page', 'conversations.cleanup.page'],
  ['POST', '/api/conversations/cleanup/remove', 'conversations.cleanup.remove'],
  ['POST', '/api/local-agents/account-usage', 'localAgents.accountUsage'],
  ['POST', '/api/conversations/artifacts/edit-target', 'conversations.artifacts.editTarget'],
  ['POST', '/api/conversations/artifacts/data-impact', 'conversations.artifacts.dataImpact'],
  ['POST', '/api/conversations/artifacts/export-data', 'conversations.artifacts.exportData'],
  ['POST', '/api/conversations/artifacts/save', 'conversations.artifacts.save'],
  ['GET', '/api/projects/tasks/attachments/abs-path', 'projects.tasks.attachments.absPath'],
  ['POST', '/api/connectors/account-choice-response', 'connectors.account_choice_response'],
  // Exact routes
  ['GET',    '/api/auth/status',              { fake: { ok: true, authenticated: true } }],
  ['GET',    '/api/user/init',                'user.init'],
  ['GET',    '/api/conversations/list',       'conversations.list'],
  ['POST',   '/api/conversations/create',     'conversations.create'],
  ['GET',    '/api/agents/list',              'agents.list'],
  ['POST',   '/api/agents/create',            'agents.create'],
  ['GET',    '/api/skills/list',              'skills.list'],
  ['GET',    '/api/skills/read',              'skills.read'],
  ['PUT',    '/api/skills/write',             'skills.writeFile'],
  ['GET',    '/api/skills/tree',              'skills.tree'],
  ['POST',   '/api/skills/create',            'skills.create'],
  ['POST',   '/api/skills/pick-import-dir',   'skills.pickImportDir'],
  ['POST',   '/api/skills/create-from-url',   'skills.createFromUrl'],
  ['POST',   '/api/skills/create-from-dir',   'skills.createFromDir'],
  ['GET',    '/api/contexts/tree',            'contexts.tree'],
  ['GET',    '/api/contexts/read',            'contexts.read'],
  ['GET',    '/api/contexts/index',           'contexts.index'],
  ['POST',   '/api/contexts/write',           'contexts.write'],
  ['PUT',    '/api/contexts/update',          'contexts.update'],
  ['POST',   '/api/contexts/mkdir',           'contexts.mkdir'],
  ['POST',   '/api/contexts/rename',          'contexts.rename'],
  ['DELETE', '/api/contexts/delete',          'contexts.delete'],
  ['POST',   '/api/contexts/upload',          { upload: 'contexts.upload' }],
  ['GET',    '/api/contexts/image',           'contexts.image'],
  ['GET',    '/api/contexts/docx',            'contexts.docxHtml'],
  ['GET',    '/api/contexts/office',          'contexts.officeHtml'],
  ['POST',   '/api/contexts/reveal',          'contexts.reveal'],
  ['POST',   '/api/library/write-text',        'library.writeText'],
  ['POST',   '/api/search/global',            'search.global'],
  ['GET',    '/api/search/status',            'search.status'],
  ['POST',   '/api/conversations/attachments/adopt', 'conversations.attachments.adopt'],
  ['POST',   '/api/common/pick-directory',    'common.pickDirectory'],
  ['GET',    '/api/kb/status',                'kb.status'],
  ['POST',   '/api/kb/reconcile',             'kb.reconcile'],
  ['POST',   '/api/kb/reprocess',             'kb.reprocess'],
  ['POST',   '/api/kb/events/stream',         'kb.events',                  null, { stream: true }],
  ['POST',   '/api/marketplace/categories',   'marketplace.categories'],
  ['POST',   '/api/marketplace/agents/list',  'marketplace.listAgents'],
  ['POST',   '/api/marketplace/skills/list',  'marketplace.listSkills'],
  ['POST',   '/api/marketplace/agents/install', 'marketplace.installAgent'],
  ['POST',   '/api/marketplace/skills/install', 'marketplace.installSkill'],
  ['POST',   '/api/marketplace/agents/upload',  'marketplace.uploadAgent'],
  ['POST',   '/api/marketplace/skills/upload',  'marketplace.uploadSkill'],

  // Pattern routes (with path parameters)
  ['DELETE', /^\/api\/conversations\/([^/]+)$/,            'conversations.delete',       ['cid']],
  ['POST',   /^\/api\/conversations\/([^/]+)\/pin$/,       'conversations.pin',          ['cid']],
  ['POST',   /^\/api\/conversations\/([^/]+)\/rename$/,    'conversations.rename',       ['cid']],
  ['POST',   /^\/api\/conversations\/([^/]+)\/move$/,      'conversations.move',         ['cid']],
  ['GET',    /^\/api\/conversations\/([^/]+)\/history$/,   'conversations.history',      ['cid']],
  ['GET',    /^\/api\/conversations\/([^/]+)\/process$/,   'conversations.processPage',  ['cid']],
  ['GET',    /^\/api\/conversations\/([^/]+)\/turns$/,     'conversations.turns',        ['cid']],
  ['GET',    /^\/api\/conversations\/([^/]+)\/files$/,     'conversations.files.list',   ['cid']],
  ['POST',   /^\/api\/conversations\/([^/]+)\/send$/,      'groupChat.send',             ['cid']],
  ['POST',   /^\/api\/conversations\/([^/]+)\/send\/stream$/, 'conversations.sendStream', ['cid'], { stream: true }],
  ['POST',   /^\/api\/conversations\/([^/]+)\/abort$/,     'groupChat.abort',            ['cid']],
  ['GET',    /^\/api\/conversations\/([^/]+)\/tasks$/,     'groupChat.tasks.list',       ['cid']],
  ['POST',   /^\/api\/conversations\/([^/]+)\/tasks\/cancel$/, 'groupChat.tasks.cancel', ['cid']],
  ['POST',   /^\/api\/conversations\/([^/]+)\/tasks\/send-now$/, 'groupChat.tasks.sendNow', ['cid']],
  ['POST',   /^\/api\/conversations\/([^/]+)\/tasks\/edit$/, 'groupChat.tasks.edit', ['cid']],
  ['POST',   /^\/api\/conversations\/([^/]+)\/tasks\/begin-edit$/, 'groupChat.tasks.beginEdit', ['cid']],
  ['POST',   /^\/api\/conversations\/([^/]+)\/tasks\/cancel-edit$/, 'groupChat.tasks.cancelEdit', ['cid']],
  ['POST',   /^\/api\/conversations\/([^/]+)\/tasks\/after$/,  'groupChat.tasks.setAfter', ['cid']],
  ['POST',   /^\/api\/conversations\/([^/]+)\/tasks\/resume-blocked$/, 'groupChat.tasks.resumeBlocked', ['cid']],
  ['POST',   /^\/api\/conversations\/([^/]+)\/tasks\/reorder$/,  'groupChat.tasks.reorder',  ['cid']],
  ['POST',   /^\/api\/conversations\/([^/]+)\/tasks\/reassign$/, 'groupChat.tasks.reassign', ['cid']],
  ['POST',   /^\/api\/conversations\/([^/]+)\/floor$/,   'groupChat.setFloor',         ['cid']],
  ['GET',    /^\/api\/conversations\/([^/]+)\/members$/,   'groupChat.listMembers',      ['cid']],
  ['GET',    /^\/api\/conversations\/([^/]+)\/runtime$/,   'groupChat.runtimeStatus',    ['cid']],
  ['POST',   /^\/api\/conversations\/([^/]+)\/events\/stream$/, 'groupChat.events',      ['cid'], { stream: true }],
  ['POST',   /^\/api\/conversations\/([^/]+)\/form-submitted$/, 'groupChat.markFormSubmitted', ['cid']],
  ['POST',   /^\/api\/conversations\/([^/]+)\/marketplace-install$/, 'groupChat.resolveMarketplaceInstallRequest', ['cid']],
  ['GET',    /^\/api\/conversations\/([^/]+)\/attachments$/,      'conversations.attachments.list',   ['cid']],
  ['POST',   /^\/api\/conversations\/([^/]+)\/attachments\/upload$/, { upload: 'conversations.attachments.upload' }, ['cid']],
  ['POST',   /^\/api\/conversations\/([^/]+)\/attachments\/import$/, 'conversations.attachments.import', ['cid']],
  ['DELETE', /^\/api\/conversations\/([^/]+)\/attachments$/,      'conversations.attachments.delete', ['cid']],
  ['GET',    /^\/api\/agents\/([^/]+)$/,                   'agents.get',                 ['agent_id']],
  ['DELETE', /^\/api\/agents\/([^/]+)$/,                   'agents.delete',              ['agent_id']],
  ['PUT',    /^\/api\/agents\/([^/]+)\/update$/,           'agents.update',              ['agent_id'], { wrapAsUpdates: true }],
  ['GET',    /^\/api\/agents\/([^/]+)\/chat$/,             'agents.chat.history',        ['agent_id']],
  ['DELETE', /^\/api\/agents\/([^/]+)\/chat$/,             'agents.chat.clear',          ['agent_id']],
  ['POST',   /^\/api\/agents\/([^/]+)\/chat\/send$/,       'agents.chat.send',           ['agent_id']],
  ['POST',   /^\/api\/agents\/([^/]+)\/chat\/send\/stream$/, 'agents.chat.sendStream',   ['id'], { stream: true }],
  ['GET',    /^\/api\/skills\/([^/]+)\/chat$/,             'skills.chat.history',        ['id']],
  ['DELETE', /^\/api\/skills\/([^/]+)\/chat$/,             'skills.chat.clear',          ['id']],
  ['POST',   /^\/api\/skills\/([^/]+)\/chat\/send$/,       'skills.chat.send',           ['id']],
  ['POST',   /^\/api\/skills\/([^/]+)\/chat\/send\/stream$/, 'skills.chat.sendStream',   ['id'], { stream: true }],
  ['PUT',    /^\/api\/skills\/([^/]+)\/update$/,           'skills.update',              ['id'], { wrapAsUpdates: true }],
  ['DELETE', /^\/api\/skills\/([^/]+)$/,                   'skills.delete',              ['id']],
];

function _matchRoute(method, pathname) {
  for (const entry of _IPC_ROUTES) {
    const [m, matcher, channel, paramKeys, opts] = entry;
    if (m !== method) continue;
    if (typeof matcher === 'string') {
      if (matcher === pathname) return { channel, params: {}, opts: opts || {} };
    } else {
      const match = matcher.exec(pathname);
      if (match) {
        const params = {};
        // Path params are URL-encoded by callers (encodeURIComponent),
        // so decode them before forwarding to the IPC handler — otherwise
        // ids that contain spaces or non-ASCII chars fail backend
        // validation (e.g. skills.isValidSkillId rejects "%20").
        (paramKeys || []).forEach((k, i) => {
          const raw = match[i + 1];
          try { params[k] = decodeURIComponent(raw); }
          catch { params[k] = raw; }
        });
        return { channel, params, opts: opts || {} };
      }
    }
  }
  return null;
}

/**
 * Build a Response-like object that the original consumer code can .json() or
 * (for streams) .body.getReader() on.
 */
function _mockJsonResponse(result) {
  if (result === null || result === undefined) {
    return _mockErrorResponse('invalid ipc response', 502);
  }
  return {
    ok: result.ok !== false,
    status: result && result.ok === false ? 400 : 200,
    json: async () => result,
  };
}

function _mockErrorResponse(error, status) {
  return {
    ok: false,
    status: status || 500,
    json: async () => ({ ok: false, error }),
  };
}

function _logIpcError(kind, channel, data) {
  try {
    if (_ipcErrorSentCount >= _IPC_ERROR_MAX_PER_SESSION) return;
    const payload = {
      channel: String(channel || '').slice(0, 120),
      ...(data || {}),
    };
    const fingerprint = [
      String(kind || ''),
      payload.channel,
      String(payload.error_name || ''),
      String(payload.error_code || ''),
      String(payload.method || ''),
      String(payload.transport || ''),
    ].join('|');
    const now = Date.now();
    const previousAt = _ipcErrorRecent.get(fingerprint) || 0;
    if (previousAt && now - previousAt < _IPC_ERROR_DEDUPE_MS) return;
    _ipcErrorRecent.set(fingerprint, now);
    if (_ipcErrorRecent.size > _IPC_ERROR_MAX_KEYS) {
      _ipcErrorRecent.delete(_ipcErrorRecent.keys().next().value);
    }
    _ipcErrorSentCount += 1;
    _shimLog.warn('IPC bridge failure', { kind, ...payload });
  } catch (_) {}
}

function _ipcFailureMeta(err) {
  const meta = {};
  const name = err && typeof err.name === 'string' ? err.name : '';
  const code = err && (typeof err.code === 'string' || typeof err.code === 'number')
    ? String(err.code)
    : '';
  if (/^[A-Za-z][A-Za-z0-9_-]{0,63}$/.test(name)) meta.error_name = name;
  if (/^[A-Za-z0-9_-]{1,64}$/.test(code)) meta.error_code = code;
  return meta;
}

function _headerValue(headers, wanted) {
  if (!headers) return '';
  if (typeof headers.get === 'function') return headers.get(wanted) || '';
  const key = Object.keys(headers).find((candidate) => candidate.toLowerCase() === wanted.toLowerCase());
  return key ? headers[key] : '';
}

function _hasOrkasInvoke() {
  return !!(window.orkas && typeof window.orkas.invoke === 'function');
}

function _hasOrkasStream() {
  return !!(window.orkas && typeof window.orkas.stream === 'function');
}

function _isStreamCancel(err) {
  const msg = err && err.message ? String(err.message) : String(err || '');
  return (err && err.name === 'AbortError') || msg === 'stream cancelled';
}

/**
 * Convert a window.orkas.stream call into a Response whose body is a
 * ReadableStream of SSE-formatted bytes. The existing app.js SSE reader
 * (`res.body.getReader()` + 'data: …\\n\\n' parse) works unchanged.
 */
function _streamResponse(channel, payload, signal) {
  const encoder = new TextEncoder();
  let streamHandle = null;

  const readable = new ReadableStream({
    start(controller) {
      streamHandle = window.orkas.stream(channel, payload, (ev) => {
        const chunk = encoder.encode('data: ' + JSON.stringify(ev) + '\n\n');
        try { controller.enqueue(chunk); } catch (_) { /* already closed */ }
      });
      // Always terminate the ReadableStream on promise settle, regardless of
      // whether the user aborted. Previously we gated close/error on an
      // `aborted` flag, which left the stream in a dangling state when the
      // renderer-side AbortController was tripped — reader.read() would hang
      // forever, the caller's try/catch/finally never ran, and the UI stayed
      // stuck in "streaming" state until the user clicked the stop button a
      // second time.
      streamHandle.promise
        .then(() => { try { controller.close(); } catch (_) {} })
        .catch((err) => {
          if (_isStreamCancel(err)) {
            try { controller.close(); } catch (_) {}
            return;
          }
          _logIpcError('ipc_stream', channel, _ipcFailureMeta(err));
          try { controller.error(new Error('ipc stream failed')); } catch (_) {}
        });
    },
    cancel() {
      if (streamHandle) streamHandle.cancel();
    },
  });

  if (signal) {
    if (signal.aborted) {
      if (streamHandle) streamHandle.cancel();
    } else {
      signal.addEventListener('abort', () => {
        if (streamHandle) streamHandle.cancel();
      });
    }
  }

  return { ok: true, status: 200, body: readable };
}

/**
 * Special-case: binary uploads that used to be multipart/binary POSTs. In IPC
 * we serialize the ArrayBuffer to base64 and send via a regular invoke channel.
 * `channel` is the IPC channel; `extraParams` is merged into the payload
 * (e.g. `{ cid }` for per-conversation attachments).
 */
async function _uploadBinary(channel, options, extraParams) {
  if (!_hasOrkasInvoke()) {
    return _mockJsonResponse({ ok: false, error: 'ipc bridge unavailable' });
  }

  const rawName = _headerValue(options.headers, 'X-Filename');
  let name = '';
  try {
    name = rawName ? decodeURIComponent(rawName) : '';
  } catch (_err) {
    return _mockJsonResponse({ ok: false, error: 'invalid filename encoding' });
  }
  const body = options.body;
  let bytes;
  if (body instanceof ArrayBuffer) bytes = new Uint8Array(body);
  else if (body && body.buffer instanceof ArrayBuffer && Number.isFinite(body.byteOffset) && Number.isFinite(body.byteLength)) {
    bytes = new Uint8Array(body.buffer, body.byteOffset, body.byteLength);
  }
  else return _mockJsonResponse({ ok: false, error: 'binary body required' });

  // Chunk-wise base64 to avoid stack blowup on large files.
  let binary = '';
  const step = 0x8000;
  for (let i = 0; i < bytes.length; i += step) {
    binary += String.fromCharCode.apply(null, bytes.subarray(i, Math.min(i + step, bytes.length)));
  }
  const data = btoa(binary);
  try {
    const result = await window.orkas.invoke(channel, { ...(extraParams || {}), name, data });
    return _mockJsonResponse(result);
  } catch (err) {
    _logIpcError('ipc_invoke', channel, { ..._ipcFailureMeta(err), transport: 'upload' });
    throw new Error('ipc upload failed');
  }
}

/**
 * Core shim — signature identical to the original `apiFetch(url, options)`.
 * Recognizes the same /api/* surface as the old HTTP server; all unknowns
 * fall through to window.fetch so static assets still load normally.
 */
function apiFetch(url, options) {
  options = options || {};
  const method = (options.method || 'GET').toUpperCase();

  // Absolute URLs and non-API paths → real fetch (e.g. static assets).
  if (typeof url !== 'string' || !url.startsWith('/api/')) {
    return fetch(url, options);
  }

  const qIdx = url.indexOf('?');
  const pathname = qIdx >= 0 ? url.slice(0, qIdx) : url;
  const searchParams = qIdx >= 0 ? new URLSearchParams(url.slice(qIdx + 1)) : new URLSearchParams();

  const route = _matchRoute(method, pathname);
  if (!route) {
    _shimLog.warn('unmatched API route', { method });
    _logIpcError('ipc_unmatched_route', 'unmatched', { method });
    return Promise.resolve(_mockErrorResponse('unknown API route', 404));
  }

  const { channel, params, opts } = route;

  // `fake` — synthetic response used by /api/auth/status (auth is gone).
  if (channel && typeof channel === 'object' && channel.fake) {
    return Promise.resolve(_mockJsonResponse(channel.fake));
  }

  // Build query payload.
  const query = {};
  for (const [k, v] of searchParams.entries()) query[k] = v;

  // Build body payload.
  let body = {};
  if (options.body && typeof options.body === 'string') {
    try { body = JSON.parse(options.body); } catch (_) { body = {}; }
  } else if (options.body && typeof options.body === 'object' && !(options.body instanceof ArrayBuffer) && !(options.body instanceof Uint8Array)) {
    body = options.body;
  }

  // Special: binary upload. `channel.upload` is the IPC channel string to
  // invoke; path params (e.g. `cid`) are merged into the payload.
  if (channel && typeof channel === 'object' && channel.upload) {
    const uploadChannel = typeof channel.upload === 'string' ? channel.upload : 'contexts.upload';
    return _uploadBinary(uploadChannel, options, params).catch(() => _mockErrorResponse('ipc upload failed', 500));
  }

  // Streaming: go through window.orkas.stream + ReadableStream body.
  if (opts.stream) {
    if (!_hasOrkasStream()) {
      return Promise.resolve(_mockJsonResponse({ ok: false, error: 'ipc stream bridge unavailable' }));
    }
    const payload = { ...query, ...body, ...params };
    return Promise.resolve(_streamResponse(channel, payload, options.signal));
  }

  // Non-stream: single invoke. `wrapAsUpdates` re-shapes body → { updates }.
  const payload = opts.wrapAsUpdates
    ? { ...params, updates: body, ...query }
    : { ...query, ...body, ...params };

  if (!_hasOrkasInvoke()) {
    return Promise.resolve(_mockJsonResponse({ ok: false, error: 'ipc bridge unavailable' }));
  }

  return window.orkas.invoke(channel, payload)
    .then((result) => {
      return _mockJsonResponse(result);
    })
    .catch((err) => {
      _logIpcError('ipc_invoke', channel, _ipcFailureMeta(err));
      return _mockErrorResponse('ipc request failed', 500);
    });
}

// The Library page keeps one file workflow while each scope uses its owning IPC.
async function apiLibraryFetch(projectId, url, options = {}) {
  if (!projectId) return apiFetch(url, options);
  const [pathname, query = ''] = url.split('?');
  const body = typeof options.body === 'string' ? JSON.parse(options.body) : {};
  const name = body.path || new URLSearchParams(query).get('path') || '';
  const invoke = (method, payload = {}) => window.orkas.invoke(method, { projectId, ...payload });
  let channel = '';
  try {
    if (pathname === '/api/kb/events/stream') {
      return _streamResponse('project.kb.events', { projectId }, options.signal);
    }
    if (pathname === '/api/contexts/upload') {
      return await _uploadBinary('projects.files.upload', options, { projectId });
    }
    if (pathname === '/api/contexts/write') {
      return await _uploadBinary('projects.files.upload', {
        headers: { 'X-Filename': encodeURIComponent(name) },
        body: new TextEncoder().encode(body.content || '').buffer,
      }, { projectId });
    }
    if (pathname === '/api/contexts/reveal') {
      channel = 'projects.files.absPath';
      const resolved = await invoke(channel, { name });
      if (!resolved.ok) return _mockJsonResponse(resolved);
      channel = 'workspace.revealPath';
      return _mockJsonResponse(await invoke(channel, { path: resolved.path }));
    }
    const routes = {
      '/api/contexts/tree': ['tree', {}],
      '/api/contexts/read': ['readText', { name, ...(new URLSearchParams(query).get('preview') === 'true' ? { preview: true } : {}) }],
      '/api/contexts/image': ['image', { name }],
      '/api/contexts/office': ['officeHtml', { name }],
      '/api/contexts/mkdir': ['mkdir', { path: name }],
      '/api/contexts/rename': ['rename', { oldName: body.src, name: body.dst }],
      '/api/contexts/delete': ['delete', { name }],
      '/api/kb/status': ['status', { skipReconcile: true }],
      '/api/kb/reconcile': ['reconcile', {}],
      '/api/kb/reprocess': ['reprocess', { name }],
    };
    const route = routes[pathname];
    if (!route) return _mockErrorResponse('unknown Library route', 404);
    channel = `projects.files.${route[0]}`;
    const result = await invoke(channel, route[1]);
    if (result.ok !== false && Array.isArray(result.tree)) {
      const normalize = (nodes) => nodes.map((node) => ({
        ...node, path: node.relPath,
        ...(node.children ? { children: normalize(node.children) } : {}),
      }));
      return _mockJsonResponse({ ...result, tree: normalize(result.tree) });
    }
    return _mockJsonResponse(result);
  } catch (err) {
    _logIpcError('ipc_invoke', channel || 'projects.files.upload', _ipcFailureMeta(err));
    return _mockErrorResponse('ipc request failed', 500);
  }
}