svamp-cli 0.2.26 → 0.2.28

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.
@@ -148,7 +148,7 @@ async function sessionBroadcast(action, args) {
148
148
  console.log(`Broadcast sent: ${action}`);
149
149
  }
150
150
  async function connectToMachineService() {
151
- const { connectAndGetMachine } = await import('./commands-DRpGTxYD.mjs');
151
+ const { connectAndGetMachine } = await import('./commands-Bs2vXq8f.mjs');
152
152
  return connectAndGetMachine();
153
153
  }
154
154
  async function inboxSend(targetSessionId, opts) {
@@ -165,7 +165,7 @@ async function inboxSend(targetSessionId, opts) {
165
165
  }
166
166
  const { server, machine } = await connectToMachineService();
167
167
  try {
168
- const { resolveSessionId } = await import('./commands-DRpGTxYD.mjs');
168
+ const { resolveSessionId } = await import('./commands-Bs2vXq8f.mjs');
169
169
  const sessions = await machine.listSessions();
170
170
  const match = resolveSessionId(sessions, targetSessionId);
171
171
  const fullTargetId = match.sessionId;
@@ -108,10 +108,20 @@ function generateCaddyConfig(listenPort, mounts, adminPort = ADMIN_PORT) {
108
108
  ]
109
109
  });
110
110
  } else {
111
+ routes.push({
112
+ match: [{ path: [`/${mount.name}`] }],
113
+ handle: [
114
+ {
115
+ handler: "static_response",
116
+ status_code: 302,
117
+ headers: { Location: [`/${mount.name}/`] }
118
+ }
119
+ ]
120
+ });
111
121
  const fileServerHandler = { handler: "file_server", root: mount.directory };
112
122
  if (mount.browse !== false) fileServerHandler.browse = {};
113
123
  routes.push({
114
- match: [{ path: [`/${mount.name}/*`, `/${mount.name}`] }],
124
+ match: [{ path: [`/${mount.name}/*`, `/${mount.name}/`] }],
115
125
  handle: [
116
126
  CORS_HEADERS_HANDLER,
117
127
  { handler: "rewrite", strip_path_prefix: `/${mount.name}` },
package/dist/cli.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { s as startDaemon, b as stopDaemon, d as daemonStatus } from './run-BTlUAfV3.mjs';
1
+ import { s as startDaemon, b as stopDaemon, d as daemonStatus } from './run-D_OwNYZr.mjs';
2
2
  import 'os';
3
3
  import 'fs/promises';
4
4
  import 'fs';
@@ -36,7 +36,7 @@ async function main() {
36
36
  await logoutFromHypha();
37
37
  } else if (subcommand === "daemon") {
38
38
  if (daemonSubcommand === "restart") {
39
- const { restartDaemon } = await import('./run-BTlUAfV3.mjs').then(function (n) { return n.k; });
39
+ const { restartDaemon } = await import('./run-D_OwNYZr.mjs').then(function (n) { return n.k; });
40
40
  await restartDaemon();
41
41
  process.exit(0);
42
42
  }
@@ -238,7 +238,7 @@ async function main() {
238
238
  console.error("svamp service: Service commands are not available in sandboxed sessions.");
239
239
  process.exit(1);
240
240
  }
241
- const { handleServiceCommand } = await import('./commands-DV2tFSXm.mjs');
241
+ const { handleServiceCommand } = await import('./commands-DauapAbb.mjs');
242
242
  await handleServiceCommand();
243
243
  } else if (subcommand === "serve") {
244
244
  const { isSandboxed: isSandboxedServe } = await import('./sandboxDetect-DNTcbgWD.mjs');
@@ -246,7 +246,7 @@ async function main() {
246
246
  console.error("svamp serve: Serve commands are not available in sandboxed sessions.");
247
247
  process.exit(1);
248
248
  }
249
- const { handleServeCommand } = await import('./serveCommands-Ci4DE-iQ.mjs');
249
+ const { handleServeCommand } = await import('./serveCommands-DlblUnsT.mjs');
250
250
  await handleServeCommand();
251
251
  process.exit(0);
252
252
  } else if (subcommand === "process" || subcommand === "proc") {
@@ -255,7 +255,7 @@ async function main() {
255
255
  console.error("svamp process: Process commands are not available in sandboxed sessions.");
256
256
  process.exit(1);
257
257
  }
258
- const { processCommand } = await import('./commands-ibBP43SF.mjs');
258
+ const { processCommand } = await import('./commands-CGfaeJTY.mjs');
259
259
  let machineId;
260
260
  const processArgs = args.slice(1);
261
261
  const mIdx = processArgs.findIndex((a) => a === "--machine" || a === "-m");
@@ -273,7 +273,7 @@ async function main() {
273
273
  } else if (!subcommand || subcommand === "start") {
274
274
  await handleInteractiveCommand();
275
275
  } else if (subcommand === "--version" || subcommand === "-v") {
276
- const pkg = await import('./package-BSQTmkvF.mjs').catch(() => ({ default: { version: "unknown" } }));
276
+ const pkg = await import('./package-CU3zzvb7.mjs').catch(() => ({ default: { version: "unknown" } }));
277
277
  console.log(`svamp version: ${pkg.default.version}`);
278
278
  } else {
279
279
  console.error(`Unknown command: ${subcommand}`);
@@ -282,7 +282,7 @@ async function main() {
282
282
  }
283
283
  }
284
284
  async function handleInteractiveCommand() {
285
- const { runInteractive } = await import('./run-DlcgeE63.mjs');
285
+ const { runInteractive } = await import('./run-B6CGgKUJ.mjs');
286
286
  const interactiveArgs = subcommand === "start" ? args.slice(1) : args;
287
287
  let directory = process.cwd();
288
288
  let resumeSessionId;
@@ -327,7 +327,7 @@ async function handleAgentCommand() {
327
327
  return;
328
328
  }
329
329
  if (agentArgs[0] === "list") {
330
- const { KNOWN_ACP_AGENTS, KNOWN_MCP_AGENTS: KNOWN_MCP_AGENTS2 } = await import('./run-BTlUAfV3.mjs').then(function (n) { return n.i; });
330
+ const { KNOWN_ACP_AGENTS, KNOWN_MCP_AGENTS: KNOWN_MCP_AGENTS2 } = await import('./run-D_OwNYZr.mjs').then(function (n) { return n.i; });
331
331
  console.log("Known agents:");
332
332
  for (const [name, config2] of Object.entries(KNOWN_ACP_AGENTS)) {
333
333
  console.log(` ${name.padEnd(12)} ${config2.command} ${config2.args.join(" ")} (ACP)`);
@@ -339,7 +339,7 @@ async function handleAgentCommand() {
339
339
  console.log('Use "svamp agent -- <command> [args]" for a custom ACP agent.');
340
340
  return;
341
341
  }
342
- const { resolveAcpAgentConfig, KNOWN_MCP_AGENTS } = await import('./run-BTlUAfV3.mjs').then(function (n) { return n.i; });
342
+ const { resolveAcpAgentConfig, KNOWN_MCP_AGENTS } = await import('./run-D_OwNYZr.mjs').then(function (n) { return n.i; });
343
343
  let cwd = process.cwd();
344
344
  const filteredArgs = [];
345
345
  for (let i = 0; i < agentArgs.length; i++) {
@@ -363,12 +363,12 @@ async function handleAgentCommand() {
363
363
  console.log(`Starting ${config.agentName} agent in ${cwd}...`);
364
364
  let backend;
365
365
  if (KNOWN_MCP_AGENTS[config.agentName]) {
366
- const { CodexMcpBackend } = await import('./run-BTlUAfV3.mjs').then(function (n) { return n.j; });
366
+ const { CodexMcpBackend } = await import('./run-D_OwNYZr.mjs').then(function (n) { return n.j; });
367
367
  backend = new CodexMcpBackend({ cwd, log: logFn });
368
368
  } else {
369
- const { AcpBackend } = await import('./run-BTlUAfV3.mjs').then(function (n) { return n.h; });
370
- const { GeminiTransport } = await import('./run-BTlUAfV3.mjs').then(function (n) { return n.G; });
371
- const { DefaultTransport } = await import('./run-BTlUAfV3.mjs').then(function (n) { return n.D; });
369
+ const { AcpBackend } = await import('./run-D_OwNYZr.mjs').then(function (n) { return n.h; });
370
+ const { GeminiTransport } = await import('./run-D_OwNYZr.mjs').then(function (n) { return n.G; });
371
+ const { DefaultTransport } = await import('./run-D_OwNYZr.mjs').then(function (n) { return n.D; });
372
372
  const transportHandler = config.agentName === "gemini" ? new GeminiTransport() : new DefaultTransport(config.agentName);
373
373
  backend = new AcpBackend({
374
374
  agentName: config.agentName,
@@ -495,7 +495,7 @@ async function handleSessionCommand() {
495
495
  process.exit(1);
496
496
  }
497
497
  }
498
- const { sessionList, sessionSpawn, sessionStop, sessionInfo, sessionMessages, sessionAttach, sessionMachines, sessionSend, sessionWait, sessionShare, sessionRalphStart, sessionRalphCancel, sessionRalphStatus, sessionInboxSend, sessionInboxList, sessionInboxRead, sessionInboxReply, sessionInboxClear } = await import('./commands-DRpGTxYD.mjs');
498
+ const { sessionList, sessionSpawn, sessionStop, sessionInfo, sessionMessages, sessionAttach, sessionMachines, sessionSend, sessionWait, sessionShare, sessionRalphStart, sessionRalphCancel, sessionRalphStatus, sessionInboxSend, sessionInboxList, sessionInboxRead, sessionInboxReply, sessionInboxClear } = await import('./commands-Bs2vXq8f.mjs');
499
499
  const parseFlagStr = (flag, shortFlag) => {
500
500
  for (let i = 1; i < sessionArgs.length; i++) {
501
501
  if ((sessionArgs[i] === flag || shortFlag) && i + 1 < sessionArgs.length) {
@@ -555,7 +555,7 @@ async function handleSessionCommand() {
555
555
  allowDomain.push(sessionArgs[++i]);
556
556
  }
557
557
  }
558
- const { parseShareArg } = await import('./commands-DRpGTxYD.mjs');
558
+ const { parseShareArg } = await import('./commands-Bs2vXq8f.mjs');
559
559
  const shareEntries = share.map((s) => parseShareArg(s));
560
560
  await sessionSpawn(agent, dir, targetMachineId, {
561
561
  message,
@@ -641,7 +641,7 @@ async function handleSessionCommand() {
641
641
  console.error("Usage: svamp session approve <session-id> [request-id] [--json]");
642
642
  process.exit(1);
643
643
  }
644
- const { sessionApprove } = await import('./commands-DRpGTxYD.mjs');
644
+ const { sessionApprove } = await import('./commands-Bs2vXq8f.mjs');
645
645
  const approveReqId = sessionArgs[2] && !sessionArgs[2].startsWith("--") ? sessionArgs[2] : void 0;
646
646
  await sessionApprove(sessionArgs[1], approveReqId, targetMachineId, {
647
647
  json: hasFlag("--json")
@@ -651,7 +651,7 @@ async function handleSessionCommand() {
651
651
  console.error("Usage: svamp session deny <session-id> [request-id] [--json]");
652
652
  process.exit(1);
653
653
  }
654
- const { sessionDeny } = await import('./commands-DRpGTxYD.mjs');
654
+ const { sessionDeny } = await import('./commands-Bs2vXq8f.mjs');
655
655
  const denyReqId = sessionArgs[2] && !sessionArgs[2].startsWith("--") ? sessionArgs[2] : void 0;
656
656
  await sessionDeny(sessionArgs[1], denyReqId, targetMachineId, {
657
657
  json: hasFlag("--json")
@@ -687,7 +687,7 @@ async function handleSessionCommand() {
687
687
  console.error("Usage: svamp session set-title <title>");
688
688
  process.exit(1);
689
689
  }
690
- const { sessionSetTitle } = await import('./agentCommands-MiAH1S9e.mjs');
690
+ const { sessionSetTitle } = await import('./agentCommands-C2yYtmsz.mjs');
691
691
  await sessionSetTitle(title);
692
692
  } else if (sessionSubcommand === "set-link") {
693
693
  const url = sessionArgs[1];
@@ -696,7 +696,7 @@ async function handleSessionCommand() {
696
696
  process.exit(1);
697
697
  }
698
698
  const label = sessionArgs[2] && !sessionArgs[2].startsWith("--") ? sessionArgs[2] : void 0;
699
- const { sessionSetLink } = await import('./agentCommands-MiAH1S9e.mjs');
699
+ const { sessionSetLink } = await import('./agentCommands-C2yYtmsz.mjs');
700
700
  await sessionSetLink(url, label);
701
701
  } else if (sessionSubcommand === "notify") {
702
702
  const message = sessionArgs[1];
@@ -705,7 +705,7 @@ async function handleSessionCommand() {
705
705
  process.exit(1);
706
706
  }
707
707
  const level = parseFlagStr("--level") || "info";
708
- const { sessionNotify } = await import('./agentCommands-MiAH1S9e.mjs');
708
+ const { sessionNotify } = await import('./agentCommands-C2yYtmsz.mjs');
709
709
  await sessionNotify(message, level);
710
710
  } else if (sessionSubcommand === "broadcast") {
711
711
  const action = sessionArgs[1];
@@ -713,7 +713,7 @@ async function handleSessionCommand() {
713
713
  console.error("Usage: svamp session broadcast <action> [args...]\nActions: open-canvas <url> [label], close-canvas, toast <message>");
714
714
  process.exit(1);
715
715
  }
716
- const { sessionBroadcast } = await import('./agentCommands-MiAH1S9e.mjs');
716
+ const { sessionBroadcast } = await import('./agentCommands-C2yYtmsz.mjs');
717
717
  await sessionBroadcast(action, sessionArgs.slice(2).filter((a) => !a.startsWith("--")));
718
718
  } else if (sessionSubcommand === "inbox") {
719
719
  const inboxSubcmd = sessionArgs[1];
@@ -724,7 +724,7 @@ async function handleSessionCommand() {
724
724
  process.exit(1);
725
725
  }
726
726
  if (agentSessionId) {
727
- const { inboxSend } = await import('./agentCommands-MiAH1S9e.mjs');
727
+ const { inboxSend } = await import('./agentCommands-C2yYtmsz.mjs');
728
728
  await inboxSend(sessionArgs[2], {
729
729
  body: sessionArgs[3],
730
730
  subject: parseFlagStr("--subject"),
@@ -739,7 +739,7 @@ async function handleSessionCommand() {
739
739
  }
740
740
  } else if (inboxSubcmd === "list" || inboxSubcmd === "ls") {
741
741
  if (agentSessionId && !sessionArgs[2]) {
742
- const { inboxList } = await import('./agentCommands-MiAH1S9e.mjs');
742
+ const { inboxList } = await import('./agentCommands-C2yYtmsz.mjs');
743
743
  await inboxList({
744
744
  unread: hasFlag("--unread"),
745
745
  limit: parseFlagInt("--limit"),
@@ -761,7 +761,7 @@ async function handleSessionCommand() {
761
761
  process.exit(1);
762
762
  }
763
763
  if (agentSessionId && !sessionArgs[3]) {
764
- const { inboxList } = await import('./agentCommands-MiAH1S9e.mjs');
764
+ const { inboxList } = await import('./agentCommands-C2yYtmsz.mjs');
765
765
  await sessionInboxRead(agentSessionId, sessionArgs[2], targetMachineId);
766
766
  } else if (sessionArgs[3]) {
767
767
  await sessionInboxRead(sessionArgs[2], sessionArgs[3], targetMachineId);
@@ -771,7 +771,7 @@ async function handleSessionCommand() {
771
771
  }
772
772
  } else if (inboxSubcmd === "reply") {
773
773
  if (agentSessionId && sessionArgs[2] && sessionArgs[3] && !sessionArgs[4]) {
774
- const { inboxReply } = await import('./agentCommands-MiAH1S9e.mjs');
774
+ const { inboxReply } = await import('./agentCommands-C2yYtmsz.mjs');
775
775
  await inboxReply(sessionArgs[2], sessionArgs[3]);
776
776
  } else if (sessionArgs[2] && sessionArgs[3] && sessionArgs[4]) {
777
777
  await sessionInboxReply(sessionArgs[2], sessionArgs[3], sessionArgs[4], targetMachineId);
@@ -807,7 +807,7 @@ async function handleMachineCommand() {
807
807
  return;
808
808
  }
809
809
  if (machineSubcommand === "share") {
810
- const { machineShare } = await import('./commands-DRpGTxYD.mjs');
810
+ const { machineShare } = await import('./commands-Bs2vXq8f.mjs');
811
811
  let machineId;
812
812
  const shareArgs = [];
813
813
  for (let i = 1; i < machineArgs.length; i++) {
@@ -837,7 +837,7 @@ async function handleMachineCommand() {
837
837
  }
838
838
  await machineShare(machineId, { add, remove, list, configPath, showConfig });
839
839
  } else if (machineSubcommand === "exec") {
840
- const { machineExec } = await import('./commands-DRpGTxYD.mjs');
840
+ const { machineExec } = await import('./commands-Bs2vXq8f.mjs');
841
841
  let machineId;
842
842
  let cwd;
843
843
  const cmdParts = [];
@@ -857,7 +857,7 @@ async function handleMachineCommand() {
857
857
  }
858
858
  await machineExec(machineId, command, cwd);
859
859
  } else if (machineSubcommand === "info") {
860
- const { machineInfo } = await import('./commands-DRpGTxYD.mjs');
860
+ const { machineInfo } = await import('./commands-Bs2vXq8f.mjs');
861
861
  let machineId;
862
862
  for (let i = 1; i < machineArgs.length; i++) {
863
863
  if ((machineArgs[i] === "--machine" || machineArgs[i] === "-m") && i + 1 < machineArgs.length) {
@@ -877,10 +877,10 @@ async function handleMachineCommand() {
877
877
  level = machineArgs[++i];
878
878
  }
879
879
  }
880
- const { machineNotify } = await import('./agentCommands-MiAH1S9e.mjs');
880
+ const { machineNotify } = await import('./agentCommands-C2yYtmsz.mjs');
881
881
  await machineNotify(message, level);
882
882
  } else if (machineSubcommand === "ls") {
883
- const { machineLs } = await import('./commands-DRpGTxYD.mjs');
883
+ const { machineLs } = await import('./commands-Bs2vXq8f.mjs');
884
884
  let machineId;
885
885
  let showHidden = false;
886
886
  let path;
@@ -2,7 +2,7 @@ import { existsSync, readFileSync } from 'node:fs';
2
2
  import { execSync } from 'node:child_process';
3
3
  import { resolve, join } from 'node:path';
4
4
  import os from 'node:os';
5
- import { l as loadSecurityContextConfig, e as resolveSecurityContext, f as buildSecurityContextFromFlags, m as mergeSecurityContexts, c as connectToHypha } from './run-BTlUAfV3.mjs';
5
+ import { l as loadSecurityContextConfig, e as resolveSecurityContext, f as buildSecurityContextFromFlags, m as mergeSecurityContexts, c as connectToHypha } from './run-D_OwNYZr.mjs';
6
6
  import 'os';
7
7
  import 'fs/promises';
8
8
  import 'fs';
@@ -1,11 +1,11 @@
1
1
  import { writeFileSync, readFileSync } from 'fs';
2
2
  import { resolve } from 'path';
3
- import { connectAndGetMachine } from './commands-DRpGTxYD.mjs';
3
+ import { connectAndGetMachine } from './commands-Bs2vXq8f.mjs';
4
4
  import 'node:fs';
5
5
  import 'node:child_process';
6
6
  import 'node:path';
7
7
  import 'node:os';
8
- import './run-BTlUAfV3.mjs';
8
+ import './run-D_OwNYZr.mjs';
9
9
  import 'os';
10
10
  import 'fs/promises';
11
11
  import 'url';
@@ -78,7 +78,7 @@ async function serviceServe(args) {
78
78
  const resolvedDir = path.resolve(directory);
79
79
  console.log(`Serving ${resolvedDir}`);
80
80
  const caddyPort = 18080;
81
- const { CaddyManager } = await import('./caddy-fJWXn1kE.mjs');
81
+ const { CaddyManager } = await import('./caddy-BMbX-mFX.mjs');
82
82
  const caddy = new CaddyManager({ listenPort: caddyPort });
83
83
  await caddy.addMount(name, resolvedDir, !noListing);
84
84
  await caddy.start();
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- export { c as connectToHypha, d as daemonStatus, g as getHyphaServerUrl, r as registerMachineService, a as registerSessionService, s as startDaemon, b as stopDaemon } from './run-BTlUAfV3.mjs';
1
+ export { c as connectToHypha, d as daemonStatus, g as getHyphaServerUrl, r as registerMachineService, a as registerSessionService, s as startDaemon, b as stopDaemon } from './run-D_OwNYZr.mjs';
2
2
  import 'os';
3
3
  import 'fs/promises';
4
4
  import 'fs';
@@ -1,5 +1,5 @@
1
1
  var name = "svamp-cli";
2
- var version = "0.2.26";
2
+ var version = "0.2.28";
3
3
  var description = "Svamp CLI — AI workspace daemon on Hypha Cloud";
4
4
  var author = "Amun AI AB";
5
5
  var license = "SEE LICENSE IN LICENSE";
@@ -2,7 +2,7 @@ import{createRequire as _pkgrollCR}from"node:module";const require=_pkgrollCR(im
2
2
  import os from 'node:os';
3
3
  import { join, resolve } from 'node:path';
4
4
  import { mkdirSync, writeFileSync, existsSync, unlinkSync, readFileSync, watch } from 'node:fs';
5
- import { c as connectToHypha, a as registerSessionService } from './run-BTlUAfV3.mjs';
5
+ import { c as connectToHypha, a as registerSessionService } from './run-D_OwNYZr.mjs';
6
6
  import { createServer } from 'node:http';
7
7
  import { spawn } from 'node:child_process';
8
8
  import { createInterface } from 'node:readline';
@@ -15,7 +15,7 @@ import { Client } from '@modelcontextprotocol/sdk/client/index.js';
15
15
  import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
16
16
  import { ElicitRequestSchema } from '@modelcontextprotocol/sdk/types.js';
17
17
  import { z } from 'zod';
18
- import { mkdir, rm, chmod, access, mkdtemp, copyFile, writeFile, stat, readdir } from 'node:fs/promises';
18
+ import { mkdir, rm, chmod, access, mkdtemp, copyFile, writeFile, stat, readdir, readFile as readFile$1 } from 'node:fs/promises';
19
19
  import { promisify } from 'node:util';
20
20
 
21
21
  let connectToServerFn = null;
@@ -1306,6 +1306,25 @@ function loadMessagesFromDisk(messagesDir, afterSeq, limit) {
1306
1306
  return { messages: [], hasMore: false };
1307
1307
  }
1308
1308
  }
1309
+ function loadMessagesFromDiskReverse(messagesDir, beforeSeq, limit) {
1310
+ const filePath = join$1(messagesDir, "messages.jsonl");
1311
+ if (!existsSync(filePath)) return { messages: [], hasMore: false };
1312
+ try {
1313
+ const lines = readFileSync(filePath, "utf-8").split("\n").filter((l) => l.trim());
1314
+ const filtered = [];
1315
+ for (const line of lines) {
1316
+ try {
1317
+ const msg = JSON.parse(line);
1318
+ if (msg.seq < beforeSeq) filtered.push(msg);
1319
+ } catch {
1320
+ }
1321
+ }
1322
+ const page = filtered.slice(-limit);
1323
+ return { messages: page, hasMore: filtered.length > limit };
1324
+ } catch {
1325
+ return { messages: [], hasMore: false };
1326
+ }
1327
+ }
1309
1328
  function appendMessage(messagesDir, sessionId, msg) {
1310
1329
  try {
1311
1330
  const filePath = join$1(messagesDir, "messages.jsonl");
@@ -1445,6 +1464,25 @@ function createSessionStore(server, sessionId, initialMetadata, initialAgentStat
1445
1464
  hasMore: filtered.length > lim
1446
1465
  };
1447
1466
  },
1467
+ getLatestMessages: async (beforeSeq, limit, context) => {
1468
+ authorizeRequest(context, metadata.sharing, "view");
1469
+ const lim = Math.min(limit ?? 100, 500);
1470
+ const latestSeq = nextSeq - 1;
1471
+ const targetBeforeSeq = beforeSeq ?? Infinity;
1472
+ const minInMemorySeq = messages.length > 0 ? messages[0].seq : Infinity;
1473
+ let pool;
1474
+ if (targetBeforeSeq <= minInMemorySeq && options?.messagesDir) {
1475
+ const diskResult = loadMessagesFromDiskReverse(options.messagesDir, targetBeforeSeq, lim);
1476
+ return { messages: diskResult.messages, hasMore: diskResult.hasMore, latestSeq };
1477
+ } else {
1478
+ const filtered = messages.filter((m) => targetBeforeSeq === Infinity ? true : m.seq < targetBeforeSeq);
1479
+ pool = filtered.slice(-lim);
1480
+ const minReturnedSeq = pool.length > 0 ? pool[0].seq : 0;
1481
+ const hasMoreInMemory = filtered.length > lim;
1482
+ const hasMoreOnDisk = minReturnedSeq > 1 && options?.messagesDir && minInMemorySeq > 1;
1483
+ return { messages: pool, hasMore: hasMoreInMemory || !!hasMoreOnDisk, latestSeq };
1484
+ }
1485
+ },
1448
1486
  sendMessage: async (content, localId, meta, context) => {
1449
1487
  authorizeRequest(context, metadata.sharing, "interact");
1450
1488
  if (localId) {
@@ -4878,6 +4916,12 @@ async function copyDirRecursive(src, dest) {
4878
4916
  }
4879
4917
  }
4880
4918
 
4919
+ var credentialStaging = /*#__PURE__*/Object.freeze({
4920
+ __proto__: null,
4921
+ sanitizeEnvForSharing: sanitizeEnvForSharing,
4922
+ stageCredentialsForSharing: stageCredentialsForSharing
4923
+ });
4924
+
4881
4925
  const DEFAULT_PROBE_INTERVAL_S = 10;
4882
4926
  const DEFAULT_PROBE_TIMEOUT_S = 5;
4883
4927
  const DEFAULT_PROBE_FAILURE_THRESHOLD = 3;
@@ -5370,6 +5414,89 @@ class ProcessSupervisor {
5370
5414
  }
5371
5415
  }
5372
5416
 
5417
+ const OAUTH_TOKEN_ENDPOINT = "https://platform.claude.com/v1/oauth/token";
5418
+ const OAUTH_CLIENT_ID = "9d1c250a-e61b-44d9-88ed-5944d1962f5e";
5419
+ const OAUTH_SCOPES = "user:profile user:inference user:sessions:claude_code user:mcp_servers user:file_upload";
5420
+ const REFRESH_BUFFER_MS = 60 * 60 * 1e3;
5421
+ const OAUTH_CHECK_INTERVAL_MS = 5 * 60 * 1e3;
5422
+ const REFRESH_TIMEOUT_MS = 15e3;
5423
+ function getCredentialsPath() {
5424
+ return join$1(homedir(), ".claude", ".credentials.json");
5425
+ }
5426
+ async function readCredentials() {
5427
+ const path = getCredentialsPath();
5428
+ if (!existsSync(path)) return null;
5429
+ try {
5430
+ const raw = await readFile$1(path, "utf-8");
5431
+ return JSON.parse(raw);
5432
+ } catch {
5433
+ return null;
5434
+ }
5435
+ }
5436
+ async function writeCredentials(creds) {
5437
+ const path = getCredentialsPath();
5438
+ await writeFile(path, JSON.stringify(creds), { mode: 384 });
5439
+ }
5440
+ async function checkAndRefreshOAuthToken(force = false, logger) {
5441
+ const log = logger?.log ?? (() => {
5442
+ });
5443
+ const creds = await readCredentials();
5444
+ if (!creds?.claudeAiOauth) {
5445
+ return { refreshed: false, error: "No Claude OAuth credentials found" };
5446
+ }
5447
+ const oauth = creds.claudeAiOauth;
5448
+ if (!oauth.refreshToken) {
5449
+ return { refreshed: false, error: "No refresh token available" };
5450
+ }
5451
+ const now = Date.now();
5452
+ const timeUntilExpiry = oauth.expiresAt - now;
5453
+ if (!force && timeUntilExpiry > REFRESH_BUFFER_MS) {
5454
+ return { refreshed: false, expiresAt: oauth.expiresAt };
5455
+ }
5456
+ const expiryDesc = timeUntilExpiry > 0 ? `expires in ${Math.round(timeUntilExpiry / 6e4)}min` : `expired ${Math.round(-timeUntilExpiry / 6e4)}min ago`;
5457
+ log(`Claude OAuth token ${expiryDesc} \u2014 refreshing...`);
5458
+ try {
5459
+ const controller = new AbortController();
5460
+ const timeout = setTimeout(() => controller.abort(), REFRESH_TIMEOUT_MS);
5461
+ const response = await fetch(OAUTH_TOKEN_ENDPOINT, {
5462
+ method: "POST",
5463
+ headers: { "Content-Type": "application/json" },
5464
+ body: JSON.stringify({
5465
+ grant_type: "refresh_token",
5466
+ refresh_token: oauth.refreshToken,
5467
+ client_id: OAUTH_CLIENT_ID,
5468
+ scope: OAUTH_SCOPES
5469
+ }),
5470
+ signal: controller.signal
5471
+ });
5472
+ clearTimeout(timeout);
5473
+ if (!response.ok) {
5474
+ const body = await response.text().catch(() => "");
5475
+ const error = `OAuth refresh failed: HTTP ${response.status} \u2014 ${body.slice(0, 200)}`;
5476
+ log(error);
5477
+ return { refreshed: false, error };
5478
+ }
5479
+ const data = await response.json();
5480
+ const newExpiresAt = now + data.expires_in * 1e3;
5481
+ creds.claudeAiOauth = {
5482
+ ...oauth,
5483
+ accessToken: data.access_token,
5484
+ refreshToken: data.refresh_token,
5485
+ expiresAt: newExpiresAt,
5486
+ ...data.scope ? { scopes: data.scope.split(" ") } : {}
5487
+ };
5488
+ await writeCredentials(creds);
5489
+ const newExpiryMin = Math.round(data.expires_in / 60);
5490
+ log(`Claude OAuth token refreshed \u2014 new expiry in ${newExpiryMin}min (${new Date(newExpiresAt).toISOString()})`);
5491
+ return { refreshed: true, expiresAt: newExpiresAt };
5492
+ } catch (err) {
5493
+ const msg = err instanceof Error ? err.message : String(err);
5494
+ const error = `OAuth refresh error: ${msg}`;
5495
+ log(error);
5496
+ return { refreshed: false, error };
5497
+ }
5498
+ }
5499
+
5373
5500
  const __filename$1 = fileURLToPath(import.meta.url);
5374
5501
  const __dirname$1 = dirname(__filename$1);
5375
5502
  const CLAUDE_SKILLS_DIR = join(os.homedir(), ".claude", "skills");
@@ -6297,7 +6424,7 @@ async function startDaemon(options) {
6297
6424
  const supervisor = new ProcessSupervisor(join(SVAMP_HOME, "processes"));
6298
6425
  await supervisor.init();
6299
6426
  const tunnels = /* @__PURE__ */ new Map();
6300
- const { ServeManager } = await import('./serveManager-BTbXyL0i.mjs');
6427
+ const { ServeManager } = await import('./serveManager-CdJgafp4.mjs');
6301
6428
  const serveManager = new ServeManager(SVAMP_HOME, (msg) => logger.log(`[SERVE] ${msg}`), hyphaServerUrl);
6302
6429
  ensureAutoInstalledSkills(logger).catch(() => {
6303
6430
  });
@@ -6822,6 +6949,14 @@ async function startDaemon(options) {
6822
6949
  if (isBillingIssue) {
6823
6950
  hint = "\n\nCheck your Claude account credits or subscription at https://console.anthropic.com.";
6824
6951
  } else if (isLoginIssue) {
6952
+ checkAndRefreshOAuthToken(true, logger).then((r) => {
6953
+ if (r.refreshed) {
6954
+ logger.log(`[Session ${sessionId}] OAuth token refreshed after auth error \u2014 retrying on next message`);
6955
+ sessionService.pushMessage({ type: "message", message: "Authentication token was refreshed automatically. Please retry your message.", level: "warning" }, "event");
6956
+ }
6957
+ }).catch((err) => {
6958
+ logger.log(`[Session ${sessionId}] Reactive OAuth refresh failed: ${err.message}`);
6959
+ });
6825
6960
  hint = "\n\nRun `claude login` in your terminal on the machine running the daemon to re-authenticate.";
6826
6961
  } else if (isResumeIssue) {
6827
6962
  hint = "\n\nThe conversation history may be corrupted. Try starting a fresh session.";
@@ -8876,10 +9011,34 @@ The automated loop has finished. Review the progress above and let me know if yo
8876
9011
  proxyTokenRefreshInterval = setInterval(refreshProxyToken, PROXY_TOKEN_REFRESH_INTERVAL_MS);
8877
9012
  logger.log("Proxy token auto-refresh enabled (every 7 days)");
8878
9013
  }
9014
+ let oauthRefreshInterval;
9015
+ const refreshOAuthAndRestageCredentials = async () => {
9016
+ try {
9017
+ const result = await checkAndRefreshOAuthToken(false, logger);
9018
+ if (result.refreshed) {
9019
+ for (const [, session] of pidToTrackedSession) {
9020
+ if (session.cleanupCredentials) {
9021
+ try {
9022
+ const { stageCredentialsForSharing: stageCredentialsForSharing2 } = await Promise.resolve().then(function () { return credentialStaging; });
9023
+ await stageCredentialsForSharing2(session.svampSessionId);
9024
+ } catch (err) {
9025
+ logger.log(`Failed to re-stage credentials for session ${session.svampSessionId}: ${err.message}`);
9026
+ }
9027
+ }
9028
+ }
9029
+ }
9030
+ } catch (err) {
9031
+ logger.log(`OAuth refresh check error: ${err.message}`);
9032
+ }
9033
+ };
9034
+ refreshOAuthAndRestageCredentials();
9035
+ oauthRefreshInterval = setInterval(refreshOAuthAndRestageCredentials, OAUTH_CHECK_INTERVAL_MS);
9036
+ logger.log("Claude OAuth token auto-refresh enabled (checking every 5 min)");
8879
9037
  const cleanup = async (source) => {
8880
9038
  logger.log(`Cleaning up (source: ${source})...`);
8881
9039
  clearInterval(heartbeatInterval);
8882
9040
  if (proxyTokenRefreshInterval) clearInterval(proxyTokenRefreshInterval);
9041
+ if (oauthRefreshInterval) clearInterval(oauthRefreshInterval);
8883
9042
  if (unhandledRejectionResetTimer) clearTimeout(unhandledRejectionResetTimer);
8884
9043
  for (const [, session] of pidToTrackedSession) {
8885
9044
  session.stopped = true;
@@ -52,7 +52,7 @@ async function handleServeCommand() {
52
52
  }
53
53
  }
54
54
  async function serveAdd(args, machineId) {
55
- const { connectAndGetMachine } = await import('./commands-DRpGTxYD.mjs');
55
+ const { connectAndGetMachine } = await import('./commands-Bs2vXq8f.mjs');
56
56
  const pos = positionalArgs(args);
57
57
  const name = pos[0];
58
58
  if (!name) {
@@ -84,7 +84,7 @@ async function serveAdd(args, machineId) {
84
84
  }
85
85
  }
86
86
  async function serveRemove(args, machineId) {
87
- const { connectAndGetMachine } = await import('./commands-DRpGTxYD.mjs');
87
+ const { connectAndGetMachine } = await import('./commands-Bs2vXq8f.mjs');
88
88
  const pos = positionalArgs(args);
89
89
  const name = pos[0];
90
90
  if (!name) {
@@ -104,7 +104,7 @@ async function serveRemove(args, machineId) {
104
104
  }
105
105
  }
106
106
  async function serveList(args, machineId) {
107
- const { connectAndGetMachine } = await import('./commands-DRpGTxYD.mjs');
107
+ const { connectAndGetMachine } = await import('./commands-Bs2vXq8f.mjs');
108
108
  const all = hasFlag(args, "--all", "-a");
109
109
  const json = hasFlag(args, "--json");
110
110
  const sessionId = getFlag(args, "--session");
@@ -137,7 +137,7 @@ async function serveList(args, machineId) {
137
137
  }
138
138
  }
139
139
  async function serveInfo(machineId) {
140
- const { connectAndGetMachine } = await import('./commands-DRpGTxYD.mjs');
140
+ const { connectAndGetMachine } = await import('./commands-Bs2vXq8f.mjs');
141
141
  const { machine, server } = await connectAndGetMachine(machineId);
142
142
  try {
143
143
  const info = await machine.serveInfo();
@@ -425,7 +425,7 @@ class ServeManager {
425
425
  this.caddyPort = await findFreePort();
426
426
  this.port = await findFreePort();
427
427
  const adminPort = await findFreePort();
428
- const { CaddyManager } = await import('./caddy-fJWXn1kE.mjs');
428
+ const { CaddyManager } = await import('./caddy-BMbX-mFX.mjs');
429
429
  this.caddy = new CaddyManager({
430
430
  listenPort: this.caddyPort,
431
431
  adminPort,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "svamp-cli",
3
- "version": "0.2.26",
3
+ "version": "0.2.28",
4
4
  "description": "Svamp CLI — AI workspace daemon on Hypha Cloud",
5
5
  "author": "Amun AI AB",
6
6
  "license": "SEE LICENSE IN LICENSE",