@docyrus/docyrus 0.0.24 → 0.0.25

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@docyrus/docyrus",
3
- "version": "0.0.24",
3
+ "version": "0.0.25",
4
4
  "private": false,
5
5
  "description": "Docyrus API CLI",
6
6
  "main": "./main.js",
@@ -0,0 +1,28 @@
1
+ ---
2
+ name: diffity-diff
3
+ description: Open the diffity diff viewer in the browser to see your changes
4
+ user-invocable: true
5
+ ---
6
+
7
+ # Diffity Diff Skill
8
+
9
+ You are opening the diffity diff viewer so the user can see their changes in the browser.
10
+
11
+ ## Arguments
12
+
13
+ - `ref` (optional): Git ref to diff (e.g. `main..feature`, `HEAD~3`) or a GitHub PR URL (e.g. `https://github.com/owner/repo/pull/123`). Defaults to working tree changes.
14
+
15
+ ## Instructions
16
+
17
+ 1. Check that `diffity` is available: run `which diffity`. If not found, tell the user to restart `docyrus coder` so the launcher can install the managed `diffity` CLI.
18
+ 2. Run `diffity <ref>` (or just `diffity` if no ref) using the Bash tool with `run_in_background: true`:
19
+ - The CLI handles everything: if an instance is already running for this repo it reuses it and opens the browser, otherwise it starts a new server and opens the browser.
20
+ - Do NOT use `&` or `--quiet` — let the Bash tool handle backgrounding.
21
+ 3. Wait 2 seconds, then run `diffity list --json` to get the port.
22
+ 4. Tell the user diffity is running. Print the URL and keep it short — don't show session IDs, hashes, or other internals. Example:
23
+
24
+ > Diffity is running at http://localhost:5391
25
+ >
26
+ > When you're ready:
27
+ > - Leave comments on the diff in your browser, then run **/diffity-resolve** to fix them
28
+ > - Or run **/diffity-review** to get an AI code review
@@ -0,0 +1,69 @@
1
+ ---
2
+ name: diffity-resolve
3
+ description: Read open review comments and resolve them by making code fixes
4
+ user-invocable: true
5
+ ---
6
+
7
+ # Diffity Resolve Skill
8
+
9
+ You are reading open review comments and resolving them by making the requested code changes.
10
+
11
+ ## Arguments
12
+
13
+ - `thread-id` (optional): Resolve a specific thread by ID instead of all open threads. Example: `/diffity-resolve abc123`
14
+
15
+ ## CLI Reference
16
+
17
+ ```
18
+ diffity agent list [--status open|resolved|dismissed] [--json]
19
+ diffity agent comment --file <path> --line <n> [--end-line <n>] [--side new|old] --body "<text>"
20
+ diffity agent general-comment --body "<text>"
21
+ diffity agent resolve <id> [--summary "<text>"]
22
+ diffity agent dismiss <id> [--reason "<text>"]
23
+ diffity agent reply <id> --body "<text>"
24
+ ```
25
+
26
+ - `--file`, `--line`, `--body` are required for `comment`
27
+ - `--end-line` defaults to `--line` (single-line comment)
28
+ - `--side` defaults to `new`
29
+ - `general-comment` creates a diff-level comment not tied to any file or line
30
+ - `<id>` accepts full UUID or 8-char prefix
31
+
32
+ ## Prerequisites
33
+
34
+ 1. Check that `diffity` is available: run `which diffity`. If not found, tell the user to restart `docyrus coder` so the launcher can install the managed `diffity` CLI.
35
+ 2. Check that a review session exists: run `diffity agent list`. If this fails with "No active review session", tell the user to start diffity first (e.g. `diffity` or **/diffity-diff**).
36
+
37
+ ## Instructions
38
+
39
+ 1. List open comment threads with full details:
40
+ ```
41
+ diffity agent list --status open --json
42
+ ```
43
+ If a `thread-id` argument was provided, filter to just that thread. The JSON output includes the full comment body, file path, line numbers, and side for each thread.
44
+ 2. If there are no open threads, tell the user there's nothing to resolve.
45
+ 3. For each open thread, check the `comments` array and the `author.type` field (`"user"` or `"agent"`) on each comment:
46
+ a. **Skip** general comments (filePath `__general__`) — these are summaries, not actionable code changes.
47
+ b. **Skip** threads where the last comment is an agent reply that asks the user a question (e.g. "Could you clarify...?") and the user hasn't responded yet — the agent is waiting for user input. Still process threads where the agent left the original comment (code suggestion, review feedback, etc.) — those are actionable.
48
+ c. **`[nit]` comments** — these are minor suggestions but still actionable. Resolve them like any other comment.
49
+ d. **`[question]` comments** (from the user) — read the question, examine the relevant code, and reply with an answer:
50
+ ```
51
+ diffity agent reply <thread-id> --body "Your answer here"
52
+ ```
53
+ Then resolve the thread with a summary of your answer.
54
+ e. Comments phrased as questions without an explicit `[question]` tag (e.g. "should we add X?" or "can we rename this?") are suggestions — treat them as actionable requests and make the change.
55
+ f. Read the comment body from the JSON output and understand what change is requested. Interpret the intent:
56
+ - If the comment suggests a code change, make the change.
57
+ - If the comment suggests adding documentation, add or update the relevant docs.
58
+ - If the comment asks a question that implies an action (e.g. "should we add X?"), treat it as a request to do that action.
59
+ - If the comment is genuinely unclear and you cannot determine what action to take, reply asking for clarification instead of silently skipping:
60
+ ```
61
+ diffity agent reply <thread-id> --body "Could you clarify what change you'd like here?"
62
+ ```
63
+ g. Read the relevant source file to understand the full context around the commented lines, then make the requested change using the Edit tool.
64
+ h. After making the change, resolve the thread with a summary:
65
+ ```
66
+ diffity agent resolve <thread-id> --summary "Fixed: <brief description of what was changed>"
67
+ ```
68
+ 4. After resolving all applicable threads, run `diffity agent list` to confirm status.
69
+ 5. Tell the user to check the browser — resolved status will appear within 2 seconds via polling.
@@ -0,0 +1,175 @@
1
+ ---
2
+ name: diffity-review
3
+ description: Review current diff and leave comments using diffity agent commands
4
+ user-invocable: true
5
+ ---
6
+
7
+ # Diffity Review Skill
8
+
9
+ You are reviewing a diff and leaving inline comments using the `diffity agent` CLI.
10
+
11
+ ## Arguments
12
+
13
+ - `ref` (optional): Git ref to review (e.g. `main..feature`, `HEAD~3`). Defaults to working tree changes. When both `ref` and `focus` are provided, use both (e.g. `/diffity-review main..feature security`).
14
+ - `focus` (optional): Focus the review on a specific area. One of: `security`, `performance`, `naming`, `errors`, `types`, `logic`. If omitted, review everything.
15
+
16
+ ## CLI Reference
17
+
18
+ ```
19
+ diffity agent list [--status open|resolved|dismissed] [--json]
20
+ diffity agent comment --file <path> --line <n> [--end-line <n>] [--side new|old] --body "<text>"
21
+ diffity agent general-comment --body "<text>"
22
+ diffity agent resolve <id> [--summary "<text>"]
23
+ diffity agent dismiss <id> [--reason "<text>"]
24
+ diffity agent reply <id> --body "<text>"
25
+ ```
26
+
27
+ - `--file`, `--line`, `--body` are required for `comment`
28
+ - `--end-line` defaults to `--line` (single-line comment)
29
+ - `--side` defaults to `new`
30
+ - `general-comment` creates a diff-level comment not tied to any file or line
31
+ - `<id>` accepts full UUID or 8-char prefix
32
+
33
+ ## Prerequisites
34
+
35
+ 1. Check that `diffity` is available: run `which diffity`. If not found, tell the user to restart `docyrus coder` so the launcher can install the managed `diffity` CLI.
36
+
37
+ ## Instructions
38
+
39
+ ### Step 1: Ensure diffity is running for the correct ref (without opening browser)
40
+
41
+ The review needs a running session whose ref matches the requested ref. A ref mismatch causes "file not in current diff" errors when adding comments.
42
+
43
+ 1. Run `diffity list --json` to get all running instances. Parse the JSON output and find the entry whose `repoRoot` matches the current repo.
44
+ 2. If a matching entry exists, compare its `ref` field against the requested ref:
45
+ - The registry stores `"work"` for working-tree sessions and the user-provided ref string (e.g. `"main"`, `"HEAD~3"`) for named refs.
46
+ - If refs **match** → reuse the session, note the port, and continue to Step 2.
47
+ - If refs **don't match** → restart: run `diffity <ref> --no-open --new` (or `diffity --no-open --new` if no ref). The `--new` flag kills the old session and starts a fresh one. Use Bash tool with `run_in_background: true`. Wait 2 seconds, then verify with `diffity list --json` and note the port.
48
+ - If **no ref was requested** and the running session's ref is not `"work"` → restart with `diffity --no-open --new` (the running session is for a named ref, but we need working-tree).
49
+ 3. If **no session is running** for this repo, start one in the background:
50
+ - Command: `diffity <ref> --no-open` (or `diffity --no-open` if no ref)
51
+ - Use Bash tool with `run_in_background: true`
52
+ - Wait 2 seconds, then verify with `diffity list --json` and note the port.
53
+
54
+ ### Step 2: Review the diff
55
+
56
+ 1. **Get the resolved diff args from diffity's API**, then run `git diff` yourself — do NOT construct the diff ref manually, as diffity uses merge-base resolution:
57
+ ```
58
+ curl -s 'http://localhost:<port>/api/diff/ref?ref=<ref>'
59
+ ```
60
+ If no ref was provided, omit the `ref` query parameter. The response is JSON with an `args` field (e.g. `"abc123def"`). Run `git diff <args>` to get the unified diff. Line numbers are in the `@@` hunk headers.
61
+ 2. Find and read all relevant CLAUDE.md files — the root CLAUDE.md and any CLAUDE.md files in directories containing modified files. These define project-specific rules that the diff must follow.
62
+
63
+ #### Understand the change before reviewing it
64
+
65
+ 3. **Summarize the change first.** Before looking for problems, build a mental model of the diff:
66
+ - What is this change trying to accomplish? (new feature, bug fix, refactor, config change)
67
+ - Which files are structural changes vs. the core logic change?
68
+ - What is the author's intent? Read commit messages (`git log --oneline <args>`) and any linked issues or PR descriptions for context.
69
+ - What are the key decisions the author made, and what constraints were they working within?
70
+
71
+ Understanding intent helps you distinguish intentional behavior from real bugs.
72
+
73
+ 4. For each changed file, read the **entire file** (not just the diff hunks) to understand the full context.
74
+ 5. **Cross-reference callers and dependents.** For any changed function signature, renamed export, modified return type, or altered behavior: grep for usages across the codebase. A function that looks correct in isolation can break every caller. Check:
75
+ - Who calls this function? Will they handle the new return value / error / null case?
76
+ - Who imports this module? Will the changed export name resolve?
77
+ - Does this type change propagate correctly to consumers?
78
+ 6. Analyze the code changes using the techniques below. If a `focus` argument was provided, concentrate on that area. Otherwise, apply all analysis passes and the signal threshold.
79
+
80
+ #### How to analyze
81
+
82
+ The diff tells you *what* changed; the surrounding code tells you whether the change is *correct*. Apply these analysis passes:
83
+
84
+ **Data flow analysis** — Trace values through the changed code. Where does each variable come from? Where does it go? Check:
85
+ - Can a value be null/undefined where the changed code assumes it isn't?
86
+ - Does the changed code handle all branches of an upstream conditional?
87
+ - If a function's return type changed, do all callers handle the new shape?
88
+ - Are there narrowing checks (e.g. `if (x)`) that the diff accidentally moved outside of?
89
+
90
+ **State and lifecycle analysis** — For stateful code (React state, database transactions, streams, event listeners):
91
+ - Does the change create a state that can't be reached or can't be exited?
92
+ - Are resources (listeners, subscriptions, file handles) still cleaned up on all paths?
93
+ - Can concurrent access corrupt shared state?
94
+ - Does the ordering of operations still satisfy invariants (e.g. init before use)?
95
+
96
+ **Contract analysis** — Check the changed code against the contracts it must satisfy:
97
+ - Does the function still satisfy what its callers expect? (Read the callers, don't guess.)
98
+ - If it implements an interface or overrides a base method, does it still conform?
99
+ - Are pre-conditions and post-conditions preserved?
100
+ - For API endpoints: does the response shape match what clients send/expect?
101
+
102
+ **Boundary analysis** — For code at system boundaries (user input, network, file I/O, IPC):
103
+ - Is user-controlled input validated before use?
104
+ - Can malformed external data crash the process or corrupt state?
105
+ - Are there injection vectors (SQL, shell, XSS, path traversal)?
106
+
107
+ **Edge case analysis** — Only for cases that *will* happen in practice, not theoretical ones:
108
+ - Empty arrays/strings, zero, negative numbers — does the code handle them?
109
+ - Off-by-one in loops, slices, or index arithmetic
110
+ - Integer overflow, division by zero where the divisor comes from input
111
+
112
+ #### What to flag
113
+
114
+ Flag real problems that would affect correctness, security, or reliability:
115
+ - Code that will fail to compile, parse, or run (syntax errors, type errors, missing imports, unresolved references)
116
+ - Logic errors that will produce wrong results (clear bugs, off-by-one errors, broken conditions)
117
+ - Security vulnerabilities in changed code (injection, XSS, auth bypass, data exposure)
118
+ - Race conditions or data loss risks you can demonstrate with a concrete scenario
119
+ - CLAUDE.md violations where you can quote the exact rule being broken
120
+ - Broken contracts — a changed function that no longer satisfies what its callers expect
121
+
122
+ Skip style concerns, linter-catchable issues, and pre-existing problems in unchanged code. Focus on the diff, not the whole file.
123
+
124
+ #### Validate before commenting
125
+
126
+ For each finding, verify it's real before posting:
127
+ - Re-read the surrounding code — many apparent bugs disappear in full context
128
+ - For "missing import" or "undefined variable" claims, grep to confirm
129
+ - For broken callers, read the actual call sites
130
+ - For CLAUDE.md violations, confirm the rule is scoped to this file
131
+
132
+ If a repeated pattern appears across files, comment on the first occurrence and mention the pattern in the general summary instead of duplicating comments.
133
+
134
+ ### Step 3: Leave comments
135
+
136
+ 1. Categorize each finding with a severity prefix in the comment body:
137
+ - `[must-fix]` — Bugs, security issues, data loss risks. Code that will break or produce wrong results.
138
+ - `[suggestion]` — Concrete improvements with a clear reason. Not style preferences — real improvements.
139
+ - `[question]` — Something unclear that needs clarification from the author.
140
+
141
+ 2. For each finding, leave an inline comment using:
142
+ ```
143
+ diffity agent comment --file <path> --line <n> [--end-line <n>] [--side new] --body "<comment>"
144
+ ```
145
+ - Use `--side new` (default) for comments on added/modified code
146
+ - Use `--side old` for comments on removed code
147
+ - Use `--end-line` when the issue spans multiple lines
148
+ - **Lead with the problem**, not background. Be specific and actionable.
149
+ - For small, self-contained fixes, include a code suggestion showing the fix
150
+ - For larger fixes (structural changes, multi-location), describe the issue and suggested approach without a full code block
151
+ - If flagging a CLAUDE.md violation, quote the exact rule being broken
152
+ 3. After leaving all inline comments, decide whether a general comment is needed:
153
+ - **No findings → leave a general comment:** "No issues found. Checked for bugs and CLAUDE.md compliance."
154
+ - **1-2 findings → skip the general comment** unless there's a cross-cutting concern the inline comments don't cover.
155
+ - **3+ findings → leave a general comment** summarizing the themes.
156
+ - **Do not use severity prefixes in the general comment** — prefixes are only for inline findings.
157
+ - Lead with the verdict, be direct and concise — no compliments, no filler, no narrating what the code does.
158
+ ```
159
+ diffity agent general-comment --body "<overall review summary>"
160
+ ```
161
+
162
+ ### Step 4: Open the browser
163
+
164
+ 1. Open the browser now that comments are ready:
165
+ ```
166
+ diffity open <ref>
167
+ ```
168
+ Pass the ref argument if one was provided (e.g. `diffity open HEAD~3`). Omit it to open the default view.
169
+ 2. Tell the user the review is ready and they can check the browser. Example:
170
+
171
+ > Review complete — check your browser.
172
+ >
173
+ > Found: 2 must-fix, 1 suggestion
174
+ >
175
+ > When you're ready, run **/diffity-resolve** to fix them.
package/server-loader.js CHANGED
@@ -3092,6 +3092,85 @@ async function waitForIdle(session, timeoutMs = 3e4) {
3092
3092
  }
3093
3093
  });
3094
3094
  }
3095
+ function convertSessionEntriesToUIMessages(entries) {
3096
+ const messages = [];
3097
+ const toolResults = /* @__PURE__ */ new Map();
3098
+ for (const entry of entries) {
3099
+ const rec = entry;
3100
+ if (rec.type !== "message") {
3101
+ continue;
3102
+ }
3103
+ const msg = rec.message;
3104
+ if (!msg || msg.role !== "toolResult") {
3105
+ continue;
3106
+ }
3107
+ const toolCallId = msg.toolCallId;
3108
+ if (toolCallId) {
3109
+ const content = msg.content;
3110
+ const textParts = Array.isArray(content) ? content.filter((b) => b.type === "text").map((b) => b.text).join("\n") : typeof content === "string" ? content : "";
3111
+ toolResults.set(toolCallId, {
3112
+ output: textParts,
3113
+ isError: msg.isError ?? false
3114
+ });
3115
+ }
3116
+ }
3117
+ for (const entry of entries) {
3118
+ const rec = entry;
3119
+ if (rec.type !== "message") {
3120
+ continue;
3121
+ }
3122
+ const msg = rec.message;
3123
+ if (!msg) {
3124
+ continue;
3125
+ }
3126
+ const entryId = rec.id ?? `entry_${messages.length}`;
3127
+ if (msg.role === "user") {
3128
+ const content = msg.content;
3129
+ let text = "";
3130
+ if (typeof content === "string") {
3131
+ text = content;
3132
+ } else if (Array.isArray(content)) {
3133
+ text = content.filter((b) => b.type === "text").map((b) => b.text).join("\n");
3134
+ }
3135
+ if (text) {
3136
+ messages.push({ id: entryId, role: "user", parts: [{ type: "text", text }] });
3137
+ }
3138
+ continue;
3139
+ }
3140
+ if (msg.role === "assistant") {
3141
+ const content = msg.content;
3142
+ if (!Array.isArray(content)) {
3143
+ continue;
3144
+ }
3145
+ const parts = [];
3146
+ for (const block of content) {
3147
+ if (block.type === "text" && typeof block.text === "string") {
3148
+ parts.push({ type: "text", text: block.text });
3149
+ } else if (block.type === "thinking" && typeof block.thinking === "string") {
3150
+ parts.push({ type: "reasoning", text: block.thinking, state: "complete" });
3151
+ } else if (block.type === "toolCall") {
3152
+ const toolCallId = block.id;
3153
+ const toolName = block.name;
3154
+ const input = block.arguments ?? {};
3155
+ const result = toolResults.get(toolCallId);
3156
+ parts.push({
3157
+ type: "dynamic-tool",
3158
+ toolCallId,
3159
+ toolName,
3160
+ input,
3161
+ state: result ? result.isError ? "output-error" : "output-available" : "input-available",
3162
+ ...result && !result.isError ? { output: result.output } : {},
3163
+ ...result && result.isError ? { errorText: String(result.output) } : {}
3164
+ });
3165
+ }
3166
+ }
3167
+ if (parts.length > 0) {
3168
+ messages.push({ id: entryId, role: "assistant", parts });
3169
+ }
3170
+ }
3171
+ }
3172
+ return messages;
3173
+ }
3095
3174
  var FS_IGNORE = /* @__PURE__ */ new Set([
3096
3175
  "node_modules",
3097
3176
  ".git",
@@ -3196,7 +3275,7 @@ async function walkFiles(params) {
3196
3275
  }
3197
3276
  }
3198
3277
  async function createAgentServer(params) {
3199
- const { port, sessionManager, modelRegistry, context, onResumeSession } = params;
3278
+ const { port, sessionManager, modelRegistry, context, onCreateSession, onResumeSession } = params;
3200
3279
  let activeSession = params.session;
3201
3280
  const app = new Hono2();
3202
3281
  app.use("/*", cors({ origin: "*" }));
@@ -3291,6 +3370,31 @@ async function createAgentServer(params) {
3291
3370
  return c.json({ error: message }, 500);
3292
3371
  }
3293
3372
  });
3373
+ app.post("/api/sessions", async (c) => {
3374
+ try {
3375
+ if (activeSession.isStreaming) {
3376
+ await activeSession.abort();
3377
+ await waitForIdle(activeSession);
3378
+ }
3379
+ activeSession = await onCreateSession();
3380
+ const sessionId = activeSession.id?.trim();
3381
+ if (!sessionId) {
3382
+ return c.json({ error: "Created session is missing an id" }, 500);
3383
+ }
3384
+ const sessions = await sessionManager.list();
3385
+ const match2 = sessions.find((session) => session.id === sessionId);
3386
+ return c.json({
3387
+ ok: true,
3388
+ sessionId,
3389
+ sessionName: match2?.name ?? null,
3390
+ cwd: match2?.cwd ?? context.cwd,
3391
+ model: activeSession.model ? { provider: activeSession.model.provider, id: activeSession.model.id } : null
3392
+ });
3393
+ } catch (error) {
3394
+ const message = error instanceof Error ? error.message : String(error);
3395
+ return c.json({ error: message }, 500);
3396
+ }
3397
+ });
3294
3398
  app.get("/api/sessions/:sessionId/messages", async (c) => {
3295
3399
  const sessionId = c.req.param("sessionId");
3296
3400
  try {
@@ -3301,14 +3405,15 @@ async function createAgentServer(params) {
3301
3405
  }
3302
3406
  const opened = sessionManager.open(match2.path);
3303
3407
  const sessionContext = opened.buildSessionContext();
3304
- const entries = opened.getBranch();
3408
+ const rawEntries = opened.getBranch();
3409
+ const messages = convertSessionEntriesToUIMessages(rawEntries);
3305
3410
  return c.json({
3306
3411
  sessionId: opened.getSessionId(),
3307
3412
  sessionName: opened.getSessionName() ?? null,
3308
3413
  cwd: opened.getCwd(),
3309
3414
  model: sessionContext.model ?? null,
3310
3415
  thinkingLevel: sessionContext.thinkingLevel ?? null,
3311
- entries
3416
+ messages
3312
3417
  });
3313
3418
  } catch (error) {
3314
3419
  const message = error instanceof Error ? error.message : String(error);
@@ -3478,6 +3583,42 @@ async function createAgentServer(params) {
3478
3583
  return c.json({ error: message }, status);
3479
3584
  }
3480
3585
  });
3586
+ const CLI_EXEC = process.env.DOCYRUS_CLI_EXECUTABLE || process.execPath;
3587
+ const CLI_ENTRY = process.env.DOCYRUS_CLI_ENTRY || (0, import_node_path2.resolve)(process.argv[1] ? (0, import_node_path2.join)(process.argv[1], "..") : __dirname, "main.js");
3588
+ const CLI_SCOPE = process.env.DOCYRUS_CLI_SCOPE;
3589
+ const CLI_TIMEOUT_MS = 3e4;
3590
+ function runCliCommand(args) {
3591
+ return new Promise((resolveResult) => {
3592
+ const scopeArgs = CLI_SCOPE ? ["--scope", CLI_SCOPE] : [];
3593
+ const proc = (0, import_node_child_process.spawn)(CLI_EXEC, [CLI_ENTRY, ...scopeArgs, ...args, "--json"], {
3594
+ cwd: context.cwd,
3595
+ stdio: ["ignore", "pipe", "pipe"],
3596
+ timeout: CLI_TIMEOUT_MS
3597
+ });
3598
+ let stdout = "";
3599
+ let stderr = "";
3600
+ proc.stdout?.on("data", (chunk) => {
3601
+ stdout += chunk.toString();
3602
+ });
3603
+ proc.stderr?.on("data", (chunk) => {
3604
+ stderr += chunk.toString();
3605
+ });
3606
+ proc.on("close", (code) => {
3607
+ if (code !== 0) {
3608
+ resolveResult({ ok: false, error: stderr.trim() || `exit code ${code}` });
3609
+ return;
3610
+ }
3611
+ try {
3612
+ resolveResult({ ok: true, data: JSON.parse(stdout) });
3613
+ } catch {
3614
+ resolveResult({ ok: true, data: stdout.trim() });
3615
+ }
3616
+ });
3617
+ proc.on("error", (err) => {
3618
+ resolveResult({ ok: false, error: err.message });
3619
+ });
3620
+ });
3621
+ }
3481
3622
  let devProcess = null;
3482
3623
  let devUrl = null;
3483
3624
  const DEV_URL_PATTERN = /https?:\/\/(?:localhost|127\.0\.0\.1):\d+/;
@@ -3538,13 +3679,57 @@ async function createAgentServer(params) {
3538
3679
  }
3539
3680
  return null;
3540
3681
  }
3682
+ let cachedProjectInfo = null;
3683
+ async function getProjectInfo() {
3684
+ if (cachedProjectInfo) {
3685
+ return cachedProjectInfo;
3686
+ }
3687
+ const cwd = context.cwd;
3688
+ let repo = null;
3689
+ let packageName = null;
3690
+ let packageVersion = null;
3691
+ try {
3692
+ repo = await new Promise((res, rej) => {
3693
+ (0, import_node_child_process.execFile)("git", ["remote", "get-url", "origin"], { cwd }, (err, stdout) => {
3694
+ if (err) {
3695
+ return rej(err);
3696
+ }
3697
+ const url = stdout.trim();
3698
+ const match2 = url.match(/\/([^/]+?)(?:\.git)?$/);
3699
+ res(match2 ? match2[1] : url);
3700
+ });
3701
+ });
3702
+ } catch {
3703
+ }
3704
+ try {
3705
+ const pkg = JSON.parse(await (0, import_promises2.readFile)((0, import_node_path2.join)(cwd, "package.json"), "utf-8"));
3706
+ packageName = pkg.name ?? null;
3707
+ packageVersion = pkg.version ?? null;
3708
+ } catch {
3709
+ }
3710
+ cachedProjectInfo = {
3711
+ path: cwd,
3712
+ folder: (0, import_node_path2.basename)(cwd),
3713
+ repo,
3714
+ packageName,
3715
+ packageVersion
3716
+ };
3717
+ return cachedProjectInfo;
3718
+ }
3541
3719
  app.get("/api/env/status", async (c) => {
3720
+ const [authResult, project] = await Promise.all([
3721
+ runCliCommand(["auth", "who"]),
3722
+ getProjectInfo()
3723
+ ]);
3724
+ const env = authResult.ok ? authResult.data : null;
3542
3725
  if (devProcess && devProcess.exitCode === null && devUrl) {
3543
3726
  const httpStatus = await probeUrl(devUrl);
3544
3727
  return c.json({
3545
3728
  status: httpStatus !== null ? "running" : "starting",
3546
3729
  url: devUrl,
3547
3730
  managed: true,
3731
+ project,
3732
+ env,
3548
3733
  ...httpStatus !== null ? { httpStatus } : {}
3549
3734
  });
3550
3735
  }
@@ -3553,7 +3738,7 @@ async function createAgentServer(params) {
3553
3738
  devProcess = null;
3554
3739
  const stoppedUrl = devUrl;
3555
3740
  devUrl = null;
3556
- return c.json({ status: "stopped", url: stoppedUrl, exitCode, managed: true });
3741
+ return c.json({ status: "stopped", url: stoppedUrl, exitCode, managed: true, project, env });
3557
3742
  }
3558
3743
  const explicitUrl = c.req.query("url");
3559
3744
  const explicitPort = c.req.query("port");
@@ -3574,10 +3759,12 @@ async function createAgentServer(params) {
3574
3759
  status: httpStatus !== null ? "running" : "stopped",
3575
3760
  url: probeTarget,
3576
3761
  httpStatus: httpStatus ?? void 0,
3577
- managed: false
3762
+ managed: false,
3763
+ project,
3764
+ env
3578
3765
  });
3579
3766
  }
3580
- return c.json({ status: "stopped", url: null, managed: false });
3767
+ return c.json({ status: "stopped", url: null, managed: false, project, env });
3581
3768
  });
3582
3769
  app.post("/api/env/serve", (c) => {
3583
3770
  if (devProcess && devProcess.exitCode === null) {
@@ -3637,10 +3824,6 @@ async function createAgentServer(params) {
3637
3824
  devUrl = null;
3638
3825
  return c.json({ status: "stopped", url: stoppedUrl, pid });
3639
3826
  });
3640
- const CLI_EXEC = process.env.DOCYRUS_CLI_EXECUTABLE || process.execPath;
3641
- const CLI_ENTRY = process.env.DOCYRUS_CLI_ENTRY;
3642
- const CLI_SCOPE = process.env.DOCYRUS_CLI_SCOPE;
3643
- const CLI_TIMEOUT_MS = 3e4;
3644
3827
  const BOOLEAN_CLI_FLAGS = /* @__PURE__ */ new Set(["json", "verbose", "global", "noAuth", "expand", "i"]);
3645
3828
  function buildCliArgs(pathSegments, query, body) {
3646
3829
  const args = [...pathSegments, "--json"];
@@ -3679,9 +3862,6 @@ async function createAgentServer(params) {
3679
3862
  return args;
3680
3863
  }
3681
3864
  app.all("/api/cli/*", async (c) => {
3682
- if (!CLI_ENTRY) {
3683
- return c.json({ error: "CLI entry path not available (DOCYRUS_CLI_ENTRY not set)" }, 500);
3684
- }
3685
3865
  const pathSegments = c.req.path.replace(/^\/api\/cli\/?/, "").split("/").filter(Boolean);
3686
3866
  if (pathSegments.length === 0) {
3687
3867
  return c.json({ error: "No command specified. Usage: /api/cli/<command>/[subcommand]/[args...]" }, 400);
@@ -3737,12 +3917,10 @@ async function createAgentServer(params) {
3737
3917
  });
3738
3918
  });
3739
3919
  const { serve: serve2 } = await Promise.resolve().then(() => (init_dist(), dist_exports));
3740
- serve2({
3741
- fetch: app.fetch,
3742
- port
3743
- }, (info) => {
3920
+ const MAX_PORT_RETRIES = 10;
3921
+ function printBanner(actualPort) {
3744
3922
  process.stderr.write(`
3745
- Agent server listening on http://localhost:${info.port}
3923
+ Agent server listening on http://localhost:${actualPort}
3746
3924
 
3747
3925
  `);
3748
3926
  process.stderr.write(` POST /api/chat \u2014 send chat messages (SSE UIMessage stream)
@@ -3752,6 +3930,8 @@ async function createAgentServer(params) {
3752
3930
  process.stderr.write(` GET /api/status \u2014 session status
3753
3931
  `);
3754
3932
  process.stderr.write(` GET /api/sessions \u2014 list sessions
3933
+ `);
3934
+ process.stderr.write(` POST /api/sessions \u2014 create a new session
3755
3935
  `);
3756
3936
  process.stderr.write(` GET /api/sessions/:sessionId/messages \u2014 session messages
3757
3937
  `);
@@ -3784,7 +3964,33 @@ async function createAgentServer(params) {
3784
3964
  process.stderr.write(` * /api/cli/** \u2014 proxy any docyrus CLI command
3785
3965
 
3786
3966
  `);
3787
- });
3967
+ }
3968
+ for (let attempt = 0; attempt < MAX_PORT_RETRIES; attempt++) {
3969
+ const candidatePort = port + attempt;
3970
+ try {
3971
+ await new Promise((resolveStart, rejectStart) => {
3972
+ const server = serve2({ fetch: app.fetch, port: candidatePort }, () => {
3973
+ printBanner(candidatePort);
3974
+ resolveStart();
3975
+ });
3976
+ server.on("error", (err) => {
3977
+ if (err.code === "EADDRINUSE") {
3978
+ process.stderr.write(` Port ${candidatePort} in use, trying ${candidatePort + 1}...
3979
+ `);
3980
+ rejectStart(err);
3981
+ } else {
3982
+ throw err;
3983
+ }
3984
+ });
3985
+ });
3986
+ return;
3987
+ } catch (err) {
3988
+ const isAddrInUse = err instanceof Error && "code" in err && err.code === "EADDRINUSE";
3989
+ if (!isAddrInUse || attempt === MAX_PORT_RETRIES - 1) {
3990
+ throw new Error(`All ports ${port}\u2013${port + MAX_PORT_RETRIES - 1} are in use`);
3991
+ }
3992
+ }
3993
+ }
3788
3994
  }
3789
3995
 
3790
3996
  // src/server/server-loader.ts
@@ -3984,6 +4190,21 @@ Or create ${modelsJsonPath}`
3984
4190
  sessionDir: request.sessionDir ?? null,
3985
4191
  thinkingLevel: request.thinking ?? null
3986
4192
  },
4193
+ onCreateSession: async () => {
4194
+ const { session: freshSession } = await pi.createAgentSession({
4195
+ cwd,
4196
+ agentDir,
4197
+ authStorage,
4198
+ modelRegistry,
4199
+ resourceLoader,
4200
+ settingsManager,
4201
+ sessionManager,
4202
+ tools: buildTools(request.profile, cwd, pi),
4203
+ model: requestedModel,
4204
+ thinkingLevel: request.thinking
4205
+ });
4206
+ return freshSession;
4207
+ },
3987
4208
  onResumeSession: async (sessionId) => {
3988
4209
  const sessions = await pi.SessionManager.list(cwd, request.sessionDir);
3989
4210
  const match2 = sessions.find((s) => s.id === sessionId);