@aiden-ade/sandbox-agent 0.1.5 → 0.1.7

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.
package/dist/index.cjs CHANGED
@@ -3404,7 +3404,7 @@ var require_websocket = __commonJS({
3404
3404
  var http = require("http");
3405
3405
  var net = require("net");
3406
3406
  var tls = require("tls");
3407
- var { randomBytes, createHash } = require("crypto");
3407
+ var { randomBytes, createHash: createHash2 } = require("crypto");
3408
3408
  var { Duplex, Readable } = require("stream");
3409
3409
  var { URL } = require("url");
3410
3410
  var PerMessageDeflate = require_permessage_deflate();
@@ -4061,7 +4061,7 @@ var require_websocket = __commonJS({
4061
4061
  abortHandshake(websocket, socket, "Invalid Upgrade header");
4062
4062
  return;
4063
4063
  }
4064
- const digest = createHash("sha1").update(key + GUID).digest("base64");
4064
+ const digest = createHash2("sha1").update(key + GUID).digest("base64");
4065
4065
  if (res.headers["sec-websocket-accept"] !== digest) {
4066
4066
  abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
4067
4067
  return;
@@ -4428,7 +4428,7 @@ var require_websocket_server = __commonJS({
4428
4428
  var EventEmitter = require("events");
4429
4429
  var http = require("http");
4430
4430
  var { Duplex } = require("stream");
4431
- var { createHash } = require("crypto");
4431
+ var { createHash: createHash2 } = require("crypto");
4432
4432
  var extension = require_extension();
4433
4433
  var PerMessageDeflate = require_permessage_deflate();
4434
4434
  var subprotocol = require_subprotocol();
@@ -4725,7 +4725,7 @@ var require_websocket_server = __commonJS({
4725
4725
  );
4726
4726
  }
4727
4727
  if (this._state > RUNNING) return abortHandshake(socket, 503);
4728
- const digest = createHash("sha1").update(key + GUID).digest("base64");
4728
+ const digest = createHash2("sha1").update(key + GUID).digest("base64");
4729
4729
  const headers = [
4730
4730
  "HTTP/1.1 101 Switching Protocols",
4731
4731
  "Upgrade: websocket",
@@ -4812,58 +4812,75 @@ var require_websocket_server = __commonJS({
4812
4812
 
4813
4813
  // ../agent-core/dist/index.js
4814
4814
  var import_child_process = require("child_process");
4815
+ var import_crypto = require("crypto");
4815
4816
  var import_fs = require("fs");
4816
4817
  var import_os = require("os");
4817
4818
  var import_path = require("path");
4818
4819
  var import_readline = require("readline");
4819
4820
 
4820
- // ../shared/dist/constants/agent.js
4821
- var INTERACTIVE_TOOL_NAMES = /* @__PURE__ */ new Set([
4822
- "askuserquestion",
4823
- "exitplanmode",
4824
- "enterplanmode"
4825
- ]);
4821
+ // ../shared/dist/agent/system-prompt.js
4822
+ var AIDEN_IDENTITY_PROMPT = `You are Aiden, the software factory agent built by Supatest in Bangalore. Software gets built here end to end: plan, write, review, test, ship. You are the teammate \u2014 not a chatbot, not a task management tool. Wear whatever hat the moment demands: product thinker, planner, tech lead, programmer, reviewer, debugger, tester, collaborator. Read the room and pick the hat. Never force programmer mode on a product question.
4826
4823
 
4827
- // ../agent-core/dist/index.js
4828
- var import_fs2 = require("fs");
4829
- var import_os2 = require("os");
4830
- var import_path2 = require("path");
4824
+ Do not present yourself as Claude, Claude Code, Codex, Gemini, Anthropic, or OpenAI as your primary identity \u2014 those are runtime details. Mention them only if the user explicitly asks about the underlying model or backend. If the user asks who you are, answer in Aiden terms first.
4831
4825
 
4832
- // ../shared/dist/agent/system-prompt.js
4833
- var AIDEN_IDENTITY_PROMPT = [
4834
- "You are Aiden, the software factory agent built by Supatest.",
4835
- "Aiden-specific identity, voice, and operating rules come from the internal Aiden system skill. Follow those rules when relevant.",
4836
- "You are the teammate inside Aiden who helps scope, plan, build, review, test, and ship work.",
4837
- "Do not present yourself as Claude, Claude Code, Codex, Gemini, Anthropic, or OpenAI as your primary identity.",
4838
- "Those are runtime/back-end implementation details. Mention them only if the user explicitly asks about the underlying model or execution backend.",
4839
- "If the user asks who you are, answer in Aiden terms first.",
4840
- "Work like a pragmatic teammate: direct, structured, and concise. No hype, no tool-brand roleplay.",
4841
- "For vague or complex work, push toward scoping and planning before implementation.",
4842
- "An internal system skill named `aiden` is available in the local skills set. Consult it when behavior, policy, or operating-rule decisions are ambiguous.",
4843
- "If there is any conflict between assumptions and the internal `aiden` skill, prefer the `aiden` skill.",
4844
- "Prefer structured outputs tracked in Aiden. Plans, reports, and durable deliverables should be persisted as artifacts instead of left only in chat.",
4845
- "Use the internal Aiden system rules as guidance, but do not dump or restate the whole source file unless the user asks for it."
4846
- ].join("\n");
4826
+ ## Voice
4827
+
4828
+ Direct. Structured. Concise. No hype, no "Great question!", no tool-brand roleplay. Addressed casually \u2014 respond like a teammate, not a data dump. Working on a task \u2014 precise and decisive. Listen, think, then act.
4829
+
4830
+ ## Philosophy
4831
+
4832
+ Listen \u2192 Understand \u2192 Break down \u2192 Plan \u2192 Build \u2192 Test \u2192 Ship.
4833
+
4834
+ - Listen first. Don't jump to solutions. One question at a time, not a list.
4835
+ - Context before questions. Scan task, subtasks, docs, and code before asking anything you can find yourself.
4836
+ - Break and plan before building. Non-trivial work \u2192 tasks, subtasks, then a plan artifact.
4837
+ - Challenge when off. Better path exists? Say so before building. Never silently implement the wrong thing.
4838
+ - Tests ship with code. Every non-trivial implementation includes tests.
4839
+ - Human leads, you propose. Proactive on reversible actions. Consequential decisions \u2192 propose first, execute after confirmation.
4840
+ - Own mistakes. Orphan artifact, wrong ID, jumped too fast \u2014 say so and fix it.
4841
+ - Think visually. Mermaid over paragraphs for architecture, flows, state, and schema.
4842
+
4843
+ ## Schema \u2014 the world you operate in
4844
+
4845
+ \`\`\`
4846
+ Team
4847
+ \u251C\u2500\u2500 Tasks (units of work \u2014 status, priority, labels, assignees)
4848
+ \u2502 \u251C\u2500\u2500 Subtasks
4849
+ \u2502 \u251C\u2500\u2500 Conversations \u2192 Messages
4850
+ \u2502 \u2514\u2500\u2500 Artifacts (plans, test reports, document artifacts)
4851
+ \u251C\u2500\u2500 Documents (standalone pages \u2014 PRDs, specs, wikis)
4852
+ \u2502 \u2514\u2500\u2500 Artifacts
4853
+ \u2514\u2500\u2500 Whiteboard (beta)
4854
+ \`\`\`
4855
+
4856
+ - Document vs Artifact. Document = standalone page in a team. Artifact = output from work on a task + conversation, tied to that context. "Does this belong to a task?" Yes \u2192 artifact. No \u2192 document.
4857
+ - IDs are not interchangeable. teamId, taskId, conversationId identify different things. Substituting one for another creates orphans \u2014 records that exist in the DB but are invisible in the UI. Use aiden MCP tools; they resolve IDs from session context when available.
4858
+
4859
+ ## Structure over chat
4860
+
4861
+ Deliverables persist as Aiden artifacts and documents, not as chat. Plans, PRDs, specs, test reports, and reviews live as structured outputs tied to team, task, and conversation. For vague or complex work, push toward scoping and planning before implementation. If a skill exists for the workflow you're in, use it instead of improvising in chat.
4862
+
4863
+ ## Proactive management
4864
+
4865
+ User describes multi-step work \u2192 tech lead hat first. What tasks, what order, what dependencies, what runs in parallel. Keep statuses current \u2014 a stale board is noise, not signal. Offer structure before jumping to code.`;
4847
4866
  var PLAN_MODE_PROMPT = [
4848
4867
  "You are in Aiden plan mode.",
4849
- "Consult the internal `aiden` skill for planning and task-management operating rules when needed.",
4850
4868
  "Analyze the task, inspect the relevant code and context, and produce a concrete implementation plan.",
4851
4869
  "Do not make code changes or execute write operations in plan mode.",
4852
4870
  "Write the plan in natural markdown. Use whatever structure best communicates the work clearly.",
4853
4871
  "Include dependencies, ordering, risks, key files/functions, and decision points where relevant.",
4854
4872
  "When the plan is ready, you MUST persist it by calling the create_plan MCP tool.",
4855
- "Pass title, content, summary, taskId, and conversationId. Include projectId too when available.",
4873
+ "Pass title, content, summary, taskId, and conversationId. Include teamId too when available.",
4856
4874
  "If create_plan fails, retry it. Do not exit plan mode until the plan is persisted successfully.",
4857
4875
  "After create_plan succeeds, call ExitPlanMode to hand the plan back for approval."
4858
4876
  ].join("\n");
4859
4877
  var TEST_MODE_PROMPT = [
4860
4878
  "You are in test mode. Verify the implemented feature carefully.",
4861
- "Consult the internal `aiden` skill for testing/reporting operating rules when needed.",
4862
4879
  "Prefer browser-based validation when available.",
4863
4880
  "Persist the outcome as a structured test report artifact with create_test_report instead of leaving it only in chat."
4864
4881
  ].join("\n");
4865
- var ASK_MODE_PROMPT = "You are in ask mode. Stay read-only and explain the code, architecture, or behavior clearly without changing files. Consult the internal `aiden` skill for behavior-policy questions when needed.";
4866
- var REVIEW_MODE_PROMPT = "You are in review mode. Inspect the relevant changes, find real issues, and summarize risks and regressions precisely. Consult the internal `aiden` skill for review-quality expectations when needed.";
4882
+ var ASK_MODE_PROMPT = "You are in ask mode. Stay read-only and explain the code, architecture, or behavior clearly without changing files.";
4883
+ var REVIEW_MODE_PROMPT = "You are in review mode. Inspect the relevant changes, find real issues, and summarize risks and regressions precisely.";
4867
4884
  function getAidenModePrompt(mode2) {
4868
4885
  switch (mode2) {
4869
4886
  case "plan":
@@ -4879,7 +4896,38 @@ function getAidenModePrompt(mode2) {
4879
4896
  }
4880
4897
  }
4881
4898
 
4899
+ // ../shared/dist/agent/session-result.js
4900
+ var SESSION_RESUME_FAILED_MESSAGE = "Session resume failed. The previous session may have expired or is no longer available. Please start a new session.";
4901
+
4902
+ // ../shared/dist/constants/agent.js
4903
+ var INTERACTIVE_TOOL_NAMES = /* @__PURE__ */ new Set([
4904
+ "askuserquestion",
4905
+ "exitplanmode",
4906
+ "enterplanmode"
4907
+ ]);
4908
+
4909
+ // ../shared/dist/constants/tasks.js
4910
+ var STATUS_OPTIONS = [
4911
+ { value: "backlog", label: "Backlog", color: "#8892a4", group: "not_started", dotClass: "text-muted-foreground", headerBg: "bg-muted/60" },
4912
+ { value: "todo", label: "Todo", color: "#6b7a96", group: "not_started", dotClass: "text-muted-foreground/70", headerBg: "bg-muted/40" },
4913
+ { value: "in_progress", label: "In Progress", color: "#c49a30", group: "active", dotClass: "text-amber-700 dark:text-amber-400", headerBg: "bg-amber-400/15" },
4914
+ { value: "running", label: "Running", color: "#6b75d6", group: "active", dotClass: "text-indigo-500 dark:text-indigo-400", headerBg: "bg-indigo-400/15" },
4915
+ { value: "waiting", label: "Waiting", color: "#c47d3a", group: "active", dotClass: "text-orange-500/80 dark:text-orange-400/80", headerBg: "bg-orange-400/15" },
4916
+ { value: "in_review", label: "In Review", color: "#8b6bbf", group: "active", dotClass: "text-violet-500 dark:text-violet-400", headerBg: "bg-violet-400/15" },
4917
+ { value: "done", label: "Done", color: "#2e9e80", group: "done", dotClass: "text-teal-600 dark:text-teal-400", headerBg: "bg-teal-400/15" },
4918
+ { value: "cancelled", label: "Cancelled", color: "#7a8295", group: "closed", dotClass: "text-muted-foreground/60", headerBg: "bg-muted/60" }
4919
+ ];
4920
+ var DEFAULT_TEAM_STATUSES = STATUS_OPTIONS.map((o) => ({
4921
+ id: o.value,
4922
+ label: o.label,
4923
+ color: o.color,
4924
+ group: o.group
4925
+ }));
4926
+
4882
4927
  // ../agent-core/dist/index.js
4928
+ var import_fs2 = require("fs");
4929
+ var import_os2 = require("os");
4930
+ var import_path2 = require("path");
4883
4931
  function formatCliSpawnError(command, error) {
4884
4932
  if (error.code === "ENOENT") {
4885
4933
  return new Error(
@@ -4900,7 +4948,7 @@ function classifyCliError(stderr, exitCode) {
4900
4948
  return "API key invalid or expired. Check your provider settings.";
4901
4949
  if (lower.includes("not logged in") || lower.includes("login required") || lower.includes("please sign in") || lower.includes("please log in") || lower.includes("sign in to") || lower.includes("log in to"))
4902
4950
  return "Not logged in. Please authenticate with this provider first.";
4903
- if (lower.includes("model not supported") || lower.includes("unsupported model") || lower.includes("model not found") || lower.includes("model not available") || lower.includes("model is not available") || lower.includes("invalid model") || lower.includes("unknown model") || lower.includes("no such model"))
4951
+ if (lower.includes("model not supported") || lower.includes("unsupported model") || lower.includes("model not found") || lower.includes("model not available") || lower.includes("model is not available") || lower.includes("invalid model") || lower.includes("unknown model") || lower.includes("no such model") || lower.includes("llm not set"))
4904
4952
  return "Model not supported by this provider. Check your provider's model list.";
4905
4953
  if (lower.includes("subscription") || lower.includes("paid plan") || lower.includes("plan required") || lower.includes("upgrade your plan") || lower.includes("only supports free") || lower.includes("not available on your") || lower.includes("requires a paid"))
4906
4954
  return "This model requires a paid subscription. Switch to a supported model or upgrade your plan.";
@@ -5041,7 +5089,6 @@ function createGenericCliBackend(options) {
5041
5089
  if (options.allowContinuation) {
5042
5090
  const IDLE_MS = options.continuationIdleMs ?? 10 * 60 * 1e3;
5043
5091
  let idleTimer = null;
5044
- let heartbeatInterval = null;
5045
5092
  const resetIdleTimer = () => {
5046
5093
  if (idleTimer) clearTimeout(idleTimer);
5047
5094
  idleTimer = setTimeout(() => {
@@ -5052,23 +5099,9 @@ function createGenericCliBackend(options) {
5052
5099
  }, IDLE_MS);
5053
5100
  };
5054
5101
  state.onNewOutput = resetIdleTimer;
5055
- state.stopHeartbeat = () => {
5056
- if (heartbeatInterval) {
5057
- clearInterval(heartbeatInterval);
5058
- heartbeatInterval = null;
5059
- }
5060
- };
5061
- state.startHeartbeat = () => {
5062
- state.stopHeartbeat?.();
5063
- void presenter.onActivity?.("background_work");
5064
- heartbeatInterval = setInterval(() => {
5065
- void presenter.onActivity?.("background_work");
5066
- }, 3e4);
5067
- };
5068
5102
  resetIdleTimer();
5069
5103
  exitCode = await exitPromise;
5070
5104
  if (idleTimer) clearTimeout(idleTimer);
5071
- state.stopHeartbeat?.();
5072
5105
  } else {
5073
5106
  const resultPromise = new Promise((resolve2) => {
5074
5107
  state.onResultReceived = () => resolve2("result_received");
@@ -5191,7 +5224,6 @@ function parseClaudeStructuredLine(line, context, state) {
5191
5224
  if (state.resultReceived && state.allowContinuation) {
5192
5225
  console.info("[claude_cli] Continuation turn detected \u2014 restarting presenter");
5193
5226
  state.resultReceived = false;
5194
- state.stopHeartbeat?.();
5195
5227
  void presenter.onStart(context.config);
5196
5228
  }
5197
5229
  state.onNewOutput?.();
@@ -5288,7 +5320,8 @@ function parseClaudeStructuredLine(line, context, state) {
5288
5320
  const subtype = typeof parsed.subtype === "string" ? parsed.subtype : "";
5289
5321
  if ((subtype === "error_during_execution" || subtype === "error_max_turns") && !state.error) {
5290
5322
  const errObj = typeof parsed.error === "object" && parsed.error !== null ? parsed.error : null;
5291
- const errMsg = typeof parsed.error === "string" && parsed.error.trim() || errObj && typeof errObj.message === "string" && errObj.message.trim() || typeof parsed.message === "string" && parsed.message.trim() || typeof parsed.result === "string" && parsed.result.trim() || subtype;
5323
+ const resumeId = context.config.runtimeSessionId?.trim() || context.config.providerSessionId?.trim();
5324
+ const errMsg = subtype === "error_during_execution" && resumeId ? SESSION_RESUME_FAILED_MESSAGE : typeof parsed.error === "string" && parsed.error.trim() || errObj && typeof errObj.message === "string" && errObj.message.trim() || typeof parsed.message === "string" && parsed.message.trim() || typeof parsed.result === "string" && parsed.result.trim() || subtype;
5292
5325
  state.error = errMsg;
5293
5326
  console.error("[claude_cli] result subtype=", subtype, "error fields:", JSON.stringify({
5294
5327
  error: parsed.error,
@@ -5322,7 +5355,6 @@ function parseClaudeStructuredLine(line, context, state) {
5322
5355
  };
5323
5356
  void presenter.onComplete(continuationResult);
5324
5357
  state.onNewOutput?.();
5325
- state.startHeartbeat?.();
5326
5358
  console.info("[claude_cli] Result received in continuation mode \u2014 keeping stdin open for background work");
5327
5359
  } else {
5328
5360
  state.onResultReceived?.();
@@ -5808,13 +5840,12 @@ function createClaudeCliBackend(command = "claude", defaultArgs = []) {
5808
5840
  if (context.config.selectedModel?.trim()) {
5809
5841
  args.push("--model", context.config.selectedModel.trim());
5810
5842
  }
5811
- if (context.config.mcpConfigPath?.trim()) {
5812
- args.push("--mcp-config", context.config.mcpConfigPath.trim());
5813
- }
5814
5843
  if (resumeId) {
5815
5844
  args.push("--resume", resumeId);
5816
5845
  console.info("[claude_cli] Resuming session", { resumeId });
5817
5846
  }
5847
+ args.push("--chrome");
5848
+ console.info("[claude_cli] Chrome flag added \u2014 final args:", args.join(" "));
5818
5849
  args.push(...defaultArgs);
5819
5850
  return createGenericCliBackend({
5820
5851
  kind: "claude_cli",
@@ -5853,6 +5884,105 @@ function createClaudeCliBackend(command = "claude", defaultArgs = []) {
5853
5884
  }
5854
5885
  };
5855
5886
  }
5887
+ function kimiSessionId(cwd) {
5888
+ let resolved = cwd;
5889
+ try {
5890
+ resolved = (0, import_fs.realpathSync)(cwd);
5891
+ } catch {
5892
+ }
5893
+ return (0, import_crypto.createHash)("md5").update(resolved).digest("hex");
5894
+ }
5895
+ function resolveKimiCliModelArg(model2) {
5896
+ const trimmed = model2?.trim();
5897
+ if (!trimmed) return void 0;
5898
+ if (trimmed === "kimi-latest" || trimmed === "kimi-k2.5" || trimmed === "kimi-k2.6") {
5899
+ return void 0;
5900
+ }
5901
+ if (trimmed.startsWith("claude-")) return void 0;
5902
+ return trimmed;
5903
+ }
5904
+ function parseKimiStructuredLine(line, context, state) {
5905
+ const presenter = context.presenter;
5906
+ if (!state.runtimeSessionId) {
5907
+ state.runtimeSessionId = kimiSessionId(context.cwd);
5908
+ }
5909
+ let parsed;
5910
+ try {
5911
+ parsed = JSON.parse(line);
5912
+ } catch {
5913
+ const text = line.trim();
5914
+ if (text.length > 0) {
5915
+ if (text.toLowerCase().includes("llm not set")) state.error = text;
5916
+ void presenter.onLog(`[kimi_cli] ${line}`);
5917
+ }
5918
+ return;
5919
+ }
5920
+ const role = typeof parsed.role === "string" ? parsed.role : "";
5921
+ const contentBlocks = Array.isArray(parsed.content) ? parsed.content : [];
5922
+ const toolCalls = Array.isArray(parsed.tool_calls) ? parsed.tool_calls : [];
5923
+ if (role === "assistant") {
5924
+ if (toolCalls.length > 0) {
5925
+ state.iterations = Math.max(state.iterations, 1);
5926
+ for (const tc of toolCalls) {
5927
+ const fn = typeof tc.function === "object" && tc.function !== null ? tc.function : {};
5928
+ const toolId = typeof tc.id === "string" ? tc.id : `kimi-tool-${Date.now()}`;
5929
+ const toolName = typeof fn.name === "string" ? fn.name : "Tool";
5930
+ let args = {};
5931
+ if (typeof fn.arguments === "string") {
5932
+ try {
5933
+ args = JSON.parse(fn.arguments);
5934
+ } catch {
5935
+ }
5936
+ } else if (typeof fn.arguments === "object" && fn.arguments !== null) {
5937
+ args = fn.arguments;
5938
+ }
5939
+ void presenter.onToolUse(toolName, args, toolId);
5940
+ }
5941
+ } else {
5942
+ const text = contentBlocks.filter((b) => b.type === "text" && typeof b.text === "string").map((b) => b.text).join("");
5943
+ if (text) {
5944
+ state.iterations = Math.max(state.iterations, 1);
5945
+ state.summary += text;
5946
+ void presenter.onAssistantText(text);
5947
+ }
5948
+ }
5949
+ return;
5950
+ }
5951
+ if (role === "tool") {
5952
+ const toolCallId = typeof parsed.tool_call_id === "string" ? parsed.tool_call_id : `kimi-tool-${Date.now()}`;
5953
+ const allText = contentBlocks.filter((b) => b.type === "text" && typeof b.text === "string").map((b) => b.text);
5954
+ const userText = allText.filter((t) => !t.startsWith("<system>")).join("\n");
5955
+ void presenter.onToolResult?.(toolCallId, userText || allText.join("\n"));
5956
+ return;
5957
+ }
5958
+ }
5959
+ function createKimiCliBackend(command = "kimi", defaultArgs = []) {
5960
+ return createGenericCliBackend({
5961
+ kind: "kimi_cli",
5962
+ supportTier: "structured",
5963
+ command,
5964
+ args: [],
5965
+ buildArgs: (context, prompt) => {
5966
+ const args = [
5967
+ "--print",
5968
+ "--output-format",
5969
+ "stream-json",
5970
+ "--work-dir",
5971
+ context.cwd
5972
+ ];
5973
+ const resumeId = context.config.runtimeSessionId?.trim() || context.config.providerSessionId?.trim();
5974
+ if (resumeId) args.push("--session", resumeId);
5975
+ const model2 = resolveKimiCliModelArg(context.config.selectedModel);
5976
+ if (model2) args.push("--model", model2);
5977
+ return [...args, ...defaultArgs, "--prompt", prompt];
5978
+ },
5979
+ augmentPrompt: (context) => {
5980
+ const base = buildPromptWithSystem(context.config, context.promptText);
5981
+ return context.config.mode === "plan" ? buildPlanModePrefix(base) : base;
5982
+ },
5983
+ parseStructuredLine: parseKimiStructuredLine
5984
+ });
5985
+ }
5856
5986
  function createGeminiCliBackend(command = "gemini", defaultArgs = []) {
5857
5987
  return createGenericCliBackend({
5858
5988
  kind: "gemini_cli",
@@ -6188,6 +6318,16 @@ function createCodexRuntimeBackend(command = "codex", defaultArgs = []) {
6188
6318
  }
6189
6319
  var DEFAULT_MODEL = "claude-sonnet-4-6";
6190
6320
  var DROID_DEFAULT_MODEL = "claude-opus-4-7";
6321
+ function defaultSelectedModelForBackend(backendKind2) {
6322
+ switch (backendKind2) {
6323
+ case "droid_cli":
6324
+ return DROID_DEFAULT_MODEL;
6325
+ case "kimi_cli":
6326
+ return void 0;
6327
+ default:
6328
+ return DEFAULT_MODEL;
6329
+ }
6330
+ }
6191
6331
  function canonicalizePath(inputPath) {
6192
6332
  try {
6193
6333
  const resolved = (0, import_path2.resolve)(inputPath);
@@ -6313,7 +6453,7 @@ Prefer relative paths and keep your work scoped to this project.`
6313
6453
  supportTier,
6314
6454
  runtimeCommand: config.runtimeCommand || this.runtime.runtimeCommand,
6315
6455
  runtimeArgs: config.runtimeArgs || this.runtime.runtimeArgs,
6316
- selectedModel: config.selectedModel || (backendKind2 === "droid_cli" ? DROID_DEFAULT_MODEL : DEFAULT_MODEL),
6456
+ selectedModel: config.selectedModel || defaultSelectedModelForBackend(backendKind2),
6317
6457
  systemPrompt: systemPromptParts.join("\n\n") || void 0
6318
6458
  };
6319
6459
  }
@@ -6325,11 +6465,11 @@ Prefer relative paths and keep your work scoped to this project.`
6325
6465
  }
6326
6466
  let runtimeConfig = this.buildRuntimeConfig(config, safeProjectPath);
6327
6467
  const cwd = runtimeConfig.worktreePath || safeProjectPath || runtimeConfig.cwd || defaultCwd;
6328
- const env = this.buildCliEnvironment();
6468
+ const env = await this.buildCliEnvironment();
6329
6469
  const promptText = this.buildPromptText(runtimeConfig);
6330
6470
  const runtimeCommand = runtimeConfig.runtimeCommand || this.runtime.runtimeCommand;
6331
6471
  const runtimeArgs = runtimeConfig.runtimeArgs || this.runtime.runtimeArgs || [];
6332
- const backend = backendKind2 === "claude_cli" ? createClaudeCliBackend(runtimeCommand || "claude", runtimeArgs) : backendKind2 === "codex_app_server" ? createCodexRuntimeBackend(runtimeCommand || "codex", runtimeArgs) : backendKind2 === "cursor_agent_cli" ? createCursorAgentCliBackend(runtimeCommand || "cursor-agent", runtimeArgs) : backendKind2 === "gemini_cli" ? createGeminiCliBackend(runtimeCommand || "gemini", runtimeArgs) : backendKind2 === "droid_cli" ? createDroidCliBackend(runtimeCommand || "droid", runtimeArgs) : backendKind2 === "opencode_cli" ? createOpencodeCliBackend(runtimeCommand || "opencode", runtimeArgs) : createGenericCliPassthroughBackend(runtimeCommand || "generic-cli", runtimeArgs);
6472
+ const backend = backendKind2 === "claude_cli" ? createClaudeCliBackend(runtimeCommand || "claude", runtimeArgs) : backendKind2 === "codex_app_server" ? createCodexRuntimeBackend(runtimeCommand || "codex", runtimeArgs) : backendKind2 === "cursor_agent_cli" ? createCursorAgentCliBackend(runtimeCommand || "cursor-agent", runtimeArgs) : backendKind2 === "gemini_cli" ? createGeminiCliBackend(runtimeCommand || "gemini", runtimeArgs) : backendKind2 === "droid_cli" ? createDroidCliBackend(runtimeCommand || "droid", runtimeArgs) : backendKind2 === "opencode_cli" ? createOpencodeCliBackend(runtimeCommand || "opencode", runtimeArgs) : backendKind2 === "kimi_cli" ? createKimiCliBackend(runtimeCommand || "kimi", runtimeArgs) : createGenericCliPassthroughBackend(runtimeCommand || "generic-cli", runtimeArgs);
6333
6473
  let lastResult = null;
6334
6474
  for (let attempt = 0; attempt <= _BaseMachineAgent.MAX_RETRIES; attempt++) {
6335
6475
  if (this.abortController?.signal.aborted) break;
@@ -6388,7 +6528,18 @@ Prefer relative paths and keep your work scoped to this project.`
6388
6528
  `[base-machine-agent] Transient error (attempt ${attempt + 1}/${_BaseMachineAgent.MAX_RETRIES + 1}), retrying in ${delayMs}ms: ${lastResult.error}`
6389
6529
  );
6390
6530
  void this.presenter.onLog(`Transient error, retrying in ${Math.round(delayMs / 1e3)}s...`);
6391
- await new Promise((resolve2) => setTimeout(resolve2, delayMs));
6531
+ await new Promise((resolve2) => {
6532
+ const signal = this.abortController?.signal;
6533
+ if (signal?.aborted) {
6534
+ resolve2();
6535
+ return;
6536
+ }
6537
+ const timeoutId = setTimeout(resolve2, delayMs);
6538
+ signal?.addEventListener("abort", () => {
6539
+ clearTimeout(timeoutId);
6540
+ resolve2();
6541
+ }, { once: true });
6542
+ });
6392
6543
  }
6393
6544
  }
6394
6545
  const normalizedResult = lastResult;
@@ -6409,13 +6560,13 @@ Prefer relative paths and keep your work scoped to this project.`
6409
6560
  runtimeArgs: config.runtimeArgs || this.runtime.runtimeArgs
6410
6561
  };
6411
6562
  this.presenter.onStart(initialConfig);
6412
- let safeProjectPath = initialConfig.projectPath;
6413
- if (initialConfig.projectPath) {
6414
- const canonicalized = canonicalizePath(initialConfig.projectPath);
6563
+ let safeProjectPath = initialConfig.teamPath;
6564
+ if (initialConfig.teamPath) {
6565
+ const canonicalized = canonicalizePath(initialConfig.teamPath);
6415
6566
  if (canonicalized) safeProjectPath = canonicalized;
6416
6567
  }
6417
6568
  if (safeProjectPath && !(0, import_fs2.existsSync)(safeProjectPath)) {
6418
- const message = `Project path no longer exists: "${safeProjectPath}". Please update the project's local path in project settings before running the agent.`;
6569
+ const message = `Local path no longer exists: "${safeProjectPath}". Please update the team's local path in team settings before running the agent.`;
6419
6570
  this.presenter.onError(message, true);
6420
6571
  const result = {
6421
6572
  success: false,
@@ -6503,28 +6654,65 @@ var CoreAgent = class extends BaseMachineAgent {
6503
6654
  });
6504
6655
  };
6505
6656
  }
6506
- buildCliEnvironment() {
6657
+ async buildCliEnvironment() {
6507
6658
  const loginEnv = process.env;
6508
6659
  const env = {};
6509
6660
  for (const [key, value2] of Object.entries(loginEnv)) {
6510
6661
  if (value2 !== void 0) env[key] = value2;
6511
6662
  }
6512
- env.PATH = `/home/user/.local/node/bin:${env.PATH ?? ""}`;
6663
+ const home = env.HOME ?? "/home/user";
6664
+ const extraPaths = [`${home}/.local/node/bin`, `${home}/.local/bin`];
6665
+ const basePath = env.PATH ?? "";
6666
+ const existingSegments = new Set(basePath.split(":").filter(Boolean));
6667
+ const missing = extraPaths.filter((p) => !existingSegments.has(p));
6668
+ env.PATH = missing.length > 0 ? `${missing.join(":")}:${basePath}` : basePath;
6513
6669
  return env;
6514
6670
  }
6515
- buildExtraSystemPromptParts(_config) {
6671
+ buildExtraSystemPromptParts(config) {
6672
+ const parts2 = [];
6673
+ if (config.taskMeta) {
6674
+ const meta = config.taskMeta;
6675
+ const lines = ["# Task Context"];
6676
+ lines.push(`- **Title**: ${meta.title}`);
6677
+ lines.push(`- **Status**: ${meta.status.replace(/_/g, " ")}`);
6678
+ if (meta.priority && meta.priority !== "none") {
6679
+ lines.push(`- **Priority**: ${meta.priority.toUpperCase()}`);
6680
+ }
6681
+ if (meta.labels && meta.labels.length > 0) {
6682
+ lines.push(`- **Labels**: ${meta.labels.join(", ")}`);
6683
+ }
6684
+ if (meta.assignees && meta.assignees.length > 0) {
6685
+ const assigneeStr = meta.assignees.map((a) => a.name ?? a.email).join(", ");
6686
+ lines.push(`- **Assignees**: ${assigneeStr}`);
6687
+ }
6688
+ if (meta.description) {
6689
+ lines.push(`- **Description**:
6690
+ ${meta.description}`);
6691
+ }
6692
+ if (meta.descriptionAttachmentIds && meta.descriptionAttachmentIds.length > 0) {
6693
+ lines.push("");
6694
+ lines.push("## Task Description Images");
6695
+ lines.push("The task description contains images. Use the `get_attachment` MCP tool to view them:");
6696
+ for (const att of meta.descriptionAttachmentIds) {
6697
+ lines.push(`- Attachment ID: \`${att.id}\` (${att.filename})`);
6698
+ }
6699
+ }
6700
+ parts2.push(lines.join("\n"));
6701
+ }
6702
+ const taskId2 = config.taskId ?? process.env.AIDEN_TASK_ID;
6703
+ const conversationId = config.conversationId ?? process.env.AIDEN_SESSION_ID;
6516
6704
  const artifactIds = [];
6517
- const envTaskId = process.env.AIDEN_TASK_ID;
6518
- const envSessionId = process.env.AIDEN_SESSION_ID;
6519
- if (envTaskId) artifactIds.push(`- taskId: "${envTaskId}"`);
6520
- if (envSessionId) artifactIds.push(`- conversationId: "${envSessionId}"`);
6521
- if (artifactIds.length === 0) return [];
6522
- return [
6523
- [
6524
- "When creating artifacts using MCP tools (create_plan, create_document_artifact, create_test_report), always pass these IDs:",
6525
- ...artifactIds
6526
- ].join("\n")
6527
- ];
6705
+ if (taskId2) artifactIds.push(`- taskId: "${taskId2}"`);
6706
+ if (conversationId) artifactIds.push(`- conversationId: "${conversationId}"`);
6707
+ if (artifactIds.length > 0) {
6708
+ parts2.push(
6709
+ [
6710
+ "When creating artifacts using MCP tools (create_plan, create_document_artifact, create_test_report), always pass these IDs:",
6711
+ ...artifactIds
6712
+ ].join("\n")
6713
+ );
6714
+ }
6715
+ return parts2;
6528
6716
  }
6529
6717
  };
6530
6718
 
@@ -10234,7 +10422,14 @@ var WSClient = class {
10234
10422
  providerSessionId: data.providerSessionId,
10235
10423
  backendKind: data.backendKind,
10236
10424
  selectedModel: data.selectedModel,
10237
- mode: data.mode
10425
+ mode: data.mode,
10426
+ taskMeta: data.taskMeta,
10427
+ workflowTools: data.workflowTools,
10428
+ runId: data.runId,
10429
+ messageId: data.messageId,
10430
+ maxIterations: data.maxIterations,
10431
+ taskId: data.taskId,
10432
+ conversationId: data.conversationId
10238
10433
  });
10239
10434
  });
10240
10435
  this.socket.on("stop", () => {
@@ -10252,7 +10447,7 @@ var WSClient = class {
10252
10447
  };
10253
10448
 
10254
10449
  // src/version.ts
10255
- var AGENT_VERSION = "0.1.5";
10450
+ var AGENT_VERSION = "0.1.7";
10256
10451
 
10257
10452
  // src/sandbox.ts
10258
10453
  async function runSandbox(config) {
@@ -10261,6 +10456,11 @@ async function runSandbox(config) {
10261
10456
  let stopped = false;
10262
10457
  let pendingMessageResolve = null;
10263
10458
  let currentAgent = null;
10459
+ let currentTaskMeta = void 0;
10460
+ let currentWorkflowTools = void 0;
10461
+ let currentMaxIterations = config.maxIterations ?? 50;
10462
+ let currentTaskId = config.taskId;
10463
+ let currentConversationId = config.sessionId;
10264
10464
  console.info("[sandbox] Connecting to WS server", { wsUrl: config.wsUrl, sessionId: config.sessionId });
10265
10465
  const wsClient = new WSClient(
10266
10466
  config.wsUrl,
@@ -10318,13 +10518,17 @@ async function runSandbox(config) {
10318
10518
  try {
10319
10519
  result = await agent.run({
10320
10520
  task: currentTask,
10321
- maxIterations: config.maxIterations || 50,
10322
- projectPath: config.projectPath,
10521
+ maxIterations: currentMaxIterations,
10522
+ teamPath: config.projectPath,
10323
10523
  cwd: config.projectPath,
10324
10524
  backendKind: activeBackendKind,
10325
10525
  mode: activeMode,
10326
10526
  selectedModel: activeModel,
10327
10527
  providerSessionId: lastProviderSessionId ?? void 0,
10528
+ taskMeta: currentTaskMeta,
10529
+ taskId: currentTaskId,
10530
+ conversationId: currentConversationId,
10531
+ workflowTools: currentWorkflowTools,
10328
10532
  images: currentImages.length > 0 ? currentImages.map((img) => ({
10329
10533
  id: img.id,
10330
10534
  data: img.data,
@@ -10365,6 +10569,21 @@ async function runSandbox(config) {
10365
10569
  if (nextPayload.mode) {
10366
10570
  activeMode = nextPayload.mode;
10367
10571
  }
10572
+ if (nextPayload.taskMeta !== void 0) {
10573
+ currentTaskMeta = nextPayload.taskMeta;
10574
+ }
10575
+ if (nextPayload.workflowTools !== void 0) {
10576
+ currentWorkflowTools = nextPayload.workflowTools;
10577
+ }
10578
+ if (nextPayload.maxIterations !== void 0) {
10579
+ currentMaxIterations = nextPayload.maxIterations;
10580
+ }
10581
+ if (nextPayload.taskId !== void 0) {
10582
+ currentTaskId = nextPayload.taskId;
10583
+ }
10584
+ if (nextPayload.conversationId !== void 0) {
10585
+ currentConversationId = nextPayload.conversationId;
10586
+ }
10368
10587
  }
10369
10588
  presenter.setSuppressSessionLifecycle(false);
10370
10589
  wsClient.close();
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":""}
package/dist/index.js ADDED
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Aiden Sandbox Agent
3
+ * Runs inside E2B sandbox, connects to WS server, executes CoreAgent.
4
+ */
5
+ import { runSandbox } from "./sandbox.js";
6
+ import { AGENT_VERSION } from "./version.js";
7
+ // Support `aiden-agent --version` for version detection without starting the agent
8
+ if (process.argv.includes("--version")) {
9
+ process.stdout.write(`${AGENT_VERSION}\n`);
10
+ process.exit(0);
11
+ }
12
+ const wsUrl = process.env.AIDEN_WS_URL;
13
+ const sessionId = process.env.AIDEN_SESSION_ID;
14
+ const taskId = process.env.AIDEN_TASK_ID;
15
+ const sessionToken = process.env.AIDEN_SESSION_TOKEN;
16
+ const task = process.env.AIDEN_TASK;
17
+ const projectPath = process.env.AIDEN_PROJECT_PATH || "/home/user/workspace";
18
+ const backendKind = process.env.AIDEN_BACKEND_KIND || "claude_cli";
19
+ const mode = process.env.AIDEN_MODE || "agent";
20
+ const model = process.env.AIDEN_MODEL;
21
+ const providerSessionId = process.env.AIDEN_PROVIDER_SESSION_ID || undefined;
22
+ if (!wsUrl || !sessionId || !taskId || !sessionToken || task == null) {
23
+ console.error("[aiden-agent] Missing required env vars: AIDEN_WS_URL, AIDEN_SESSION_ID, AIDEN_TASK_ID, AIDEN_SESSION_TOKEN, AIDEN_TASK");
24
+ process.exit(1);
25
+ }
26
+ console.info("[aiden-agent] Starting", { sessionId, taskId, projectPath, backendKind, mode, model, version: AGENT_VERSION });
27
+ runSandbox({
28
+ wsUrl,
29
+ sessionId,
30
+ taskId,
31
+ sessionToken,
32
+ task,
33
+ projectPath,
34
+ backendKind,
35
+ mode,
36
+ model,
37
+ providerSessionId,
38
+ maxIterations: 50,
39
+ }).catch((error) => {
40
+ console.error("[aiden-agent] Fatal error:", error);
41
+ process.exit(1);
42
+ });
43
+ //# sourceMappingURL=index.js.map