wave-agent-sdk 1.0.10 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/dist/agent.d.ts +9 -6
  2. package/dist/agent.js +35 -33
  3. package/dist/builtin/skills/settings.js +31 -6
  4. package/dist/index.d.ts +2 -0
  5. package/dist/index.js +2 -0
  6. package/dist/managers/aiManager.d.ts +10 -0
  7. package/dist/managers/aiManager.js +31 -4
  8. package/dist/managers/subagentManager.d.ts +1 -0
  9. package/dist/managers/subagentManager.js +5 -1
  10. package/dist/services/hook.js +41 -7
  11. package/dist/services/initializationService.js +0 -21
  12. package/dist/services/jsonlHandler.d.ts +37 -2
  13. package/dist/services/jsonlHandler.js +55 -6
  14. package/dist/services/session.d.ts +35 -4
  15. package/dist/services/session.js +233 -36
  16. package/dist/services/worktreeHooks.d.ts +45 -0
  17. package/dist/services/worktreeHooks.js +133 -0
  18. package/dist/tools/agentTool.js +36 -1
  19. package/dist/tools/bashTool.js +120 -57
  20. package/dist/tools/enterWorktreeTool.d.ts +1 -1
  21. package/dist/tools/enterWorktreeTool.js +44 -31
  22. package/dist/tools/exitWorktreeTool.js +21 -26
  23. package/dist/types/agent.d.ts +5 -0
  24. package/dist/types/hooks.d.ts +3 -2
  25. package/dist/types/skills.d.ts +0 -1
  26. package/dist/types/skills.js +0 -1
  27. package/dist/utils/asyncWorkRegistry.d.ts +32 -0
  28. package/dist/utils/asyncWorkRegistry.js +81 -0
  29. package/dist/utils/containerSetup.js +5 -0
  30. package/dist/utils/skillParser.js +3 -6
  31. package/dist/utils/windowsPaths.d.ts +28 -0
  32. package/dist/utils/windowsPaths.js +47 -0
  33. package/dist/utils/worktreeSession.d.ts +6 -0
  34. package/dist/utils/worktreeUtils.d.ts +7 -0
  35. package/dist/utils/worktreeUtils.js +88 -40
  36. package/package.json +5 -3
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Registry of live async work that must drain before the agent is destroyed.
3
+ *
4
+ * Fire-and-forget work (dispatch, background subagents, fork subagents)
5
+ * registers its promise here so destroy() can wait deterministically instead
6
+ * of silently abandoning it (the "ghost work" class of #1808). The registry
7
+ * swallows rejections so an unregistered fire-and-forget caller can't turn a
8
+ * settled-then-removed promise into an unhandled rejection.
9
+ */
10
+ export declare class AsyncWorkRegistry {
11
+ private readonly drainTimeoutMs;
12
+ private work;
13
+ private waiters;
14
+ constructor(drainTimeoutMs?: number);
15
+ get size(): number;
16
+ isEmpty(): boolean;
17
+ /**
18
+ * Register a promise as live work. The promise is removed when it settles
19
+ * (fulfilled or rejected); rejections are consumed here so tracking never
20
+ * produces an unhandled rejection. Returns the original promise unchanged
21
+ * so the caller can still await it.
22
+ */
23
+ track<T>(promise: Promise<T>): Promise<T>;
24
+ private remove;
25
+ /**
26
+ * Wait until the registry is empty, or until the timeout elapses. Loops
27
+ * until empty: work registered after an await point is still drained.
28
+ * Returns true if drained, false on timeout (leftover work is no longer
29
+ * lifecycle-managed).
30
+ */
31
+ drain(timeoutMs?: number): Promise<boolean>;
32
+ }
@@ -0,0 +1,81 @@
1
+ /**
2
+ * Registry of live async work that must drain before the agent is destroyed.
3
+ *
4
+ * Fire-and-forget work (dispatch, background subagents, fork subagents)
5
+ * registers its promise here so destroy() can wait deterministically instead
6
+ * of silently abandoning it (the "ghost work" class of #1808). The registry
7
+ * swallows rejections so an unregistered fire-and-forget caller can't turn a
8
+ * settled-then-removed promise into an unhandled rejection.
9
+ */
10
+ export class AsyncWorkRegistry {
11
+ constructor(drainTimeoutMs = 10000) {
12
+ this.drainTimeoutMs = drainTimeoutMs;
13
+ this.work = new Set();
14
+ this.waiters = [];
15
+ }
16
+ get size() {
17
+ return this.work.size;
18
+ }
19
+ isEmpty() {
20
+ return this.work.size === 0;
21
+ }
22
+ /**
23
+ * Register a promise as live work. The promise is removed when it settles
24
+ * (fulfilled or rejected); rejections are consumed here so tracking never
25
+ * produces an unhandled rejection. Returns the original promise unchanged
26
+ * so the caller can still await it.
27
+ */
28
+ track(promise) {
29
+ this.work.add(promise);
30
+ promise.then(() => this.remove(promise), () => this.remove(promise));
31
+ return promise;
32
+ }
33
+ remove(promise) {
34
+ this.work.delete(promise);
35
+ if (this.work.size === 0) {
36
+ const waiters = this.waiters;
37
+ this.waiters = [];
38
+ for (const resolve of waiters) {
39
+ resolve();
40
+ }
41
+ }
42
+ }
43
+ /**
44
+ * Wait until the registry is empty, or until the timeout elapses. Loops
45
+ * until empty: work registered after an await point is still drained.
46
+ * Returns true if drained, false on timeout (leftover work is no longer
47
+ * lifecycle-managed).
48
+ */
49
+ async drain(timeoutMs = this.drainTimeoutMs) {
50
+ const deadline = Date.now() + timeoutMs;
51
+ while (this.work.size > 0) {
52
+ const remaining = deadline - Date.now();
53
+ if (remaining <= 0) {
54
+ return false;
55
+ }
56
+ // Wait for the registry to empty, or for the timeout — whichever comes
57
+ // first (a tracked promise may never settle).
58
+ let waiter;
59
+ const notified = new Promise((resolve) => {
60
+ waiter = resolve;
61
+ this.waiters.push(resolve);
62
+ });
63
+ let timer;
64
+ const timedOut = new Promise((resolve) => {
65
+ timer = setTimeout(resolve, remaining);
66
+ });
67
+ await Promise.race([notified, timedOut]);
68
+ if (timer)
69
+ clearTimeout(timer);
70
+ // If the timer won, the work set is still non-empty: drop our waiter so
71
+ // a later drain isn't woken by a stale notification. If notified won,
72
+ // remove() already cleared the waiters array.
73
+ if (waiter && this.work.size > 0) {
74
+ const idx = this.waiters.indexOf(waiter);
75
+ if (idx >= 0)
76
+ this.waiters.splice(idx, 1);
77
+ }
78
+ }
79
+ return true;
80
+ }
81
+ }
@@ -27,6 +27,7 @@ import { MemoryService } from "../services/memory.js";
27
27
  import { AutoMemoryService } from "../services/autoMemoryService.js";
28
28
  import { USER_MEMORY_FILE } from "./constants.js";
29
29
  import { getGitMainRepoRoot } from "./gitUtils.js";
30
+ import { AsyncWorkRegistry } from "./asyncWorkRegistry.js";
30
31
  import { logger } from "./globalLogger.js";
31
32
  import { authService } from "../services/authService.js";
32
33
  import { remoteSettingsService } from "../services/remoteSettingsService.js";
@@ -45,6 +46,10 @@ export function setupAgentContainer(setupOptions) {
45
46
  container.register("WorktreeSession", null);
46
47
  const messageQueue = new MessageQueue();
47
48
  container.register("MessageQueue", messageQueue);
49
+ // Registry of live async work that must drain before the agent is destroyed
50
+ // (dispatch, background subagents, fork subagents — the fire-and-forget work
51
+ // sites). destroy() awaits its drain() so no async work can outlive the agent.
52
+ container.register("AsyncWorkRegistry", new AsyncWorkRegistry());
48
53
  const foregroundTaskManager = new ForegroundTaskManager(container);
49
54
  container.register("ForegroundTaskManager", foregroundTaskManager);
50
55
  container.register("ConfigurationService", configurationService);
@@ -147,7 +147,6 @@ export function validateSkillMetadata(metadata) {
147
147
  // Import SKILL_DEFAULTS dynamically to avoid circular imports
148
148
  const NAME_PATTERN = /^[a-z0-9-]+$/;
149
149
  const MAX_NAME_LENGTH = 64;
150
- const MAX_DESCRIPTION_LENGTH = 1024;
151
150
  const MIN_DESCRIPTION_LENGTH = 1;
152
151
  // Validate name
153
152
  if (!metadata.name) {
@@ -161,7 +160,8 @@ export function validateSkillMetadata(metadata) {
161
160
  errors.push("Skill name must contain only lowercase letters, numbers, and hyphens");
162
161
  }
163
162
  }
164
- // Validate description
163
+ // Validate description (no length limit, aligned with Claude Code which
164
+ // truncates long descriptions at render time instead of rejecting the skill)
165
165
  if (!metadata.description) {
166
166
  errors.push("Skill description is required");
167
167
  }
@@ -169,9 +169,6 @@ export function validateSkillMetadata(metadata) {
169
169
  if (metadata.description.length < MIN_DESCRIPTION_LENGTH) {
170
170
  errors.push(`Skill description must be at least ${MIN_DESCRIPTION_LENGTH} character`);
171
171
  }
172
- if (metadata.description.length > MAX_DESCRIPTION_LENGTH) {
173
- errors.push(`Skill description must be ${MAX_DESCRIPTION_LENGTH} characters or less`);
174
- }
175
172
  }
176
173
  return errors;
177
174
  }
@@ -194,7 +191,7 @@ export function formatSkillError(skillPath, errors) {
194
191
  " 1. Ensure SKILL.md has valid YAML frontmatter (---...---)",
195
192
  " 2. Include required fields: name and description",
196
193
  " 3. Use lowercase letters, numbers, and hyphens only for name",
197
- " 4. Keep name under 64 characters and description under 1024 characters",
194
+ " 4. Keep name under 64 characters",
198
195
  ].join("\n");
199
196
  return `${header}\n${errorList}\n\n${suggestions}`;
200
197
  }
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Windows path conversion utilities for Git Bash (POSIX shell) execution.
3
+ *
4
+ * Hook commands on Windows are executed via Git Bash instead of cmd.exe
5
+ * (cmd.exe does not strip quotes from arguments after the first token, so
6
+ * `node "C:\path\script.js"` silently fails — see issue #1773). Git Bash
7
+ * cannot resolve Windows paths like `C:\Users\foo`: backslashes are treated
8
+ * as escape characters and the drive letter breaks POSIX semantics. These
9
+ * helpers convert Windows paths to the POSIX form Git Bash expects
10
+ * (`C:\Users\foo` → `/c/Users/foo`), matching Claude Code's
11
+ * `windowsPathToPosixPath`.
12
+ */
13
+ /**
14
+ * Convert a single Windows path to POSIX form for Git Bash:
15
+ * - `C:\Users\foo` → `/c/Users/foo`
16
+ * - `C:/Users/foo` → `/c/Users/foo`
17
+ * - `\\server\share` → `//server/share` (UNC preserved)
18
+ * - Already POSIX or relative paths are returned with slashes flipped.
19
+ */
20
+ export declare function windowsPathToPosixPath(p: string): string;
21
+ /**
22
+ * Convert every Windows absolute path inside a shell command string to POSIX
23
+ * form so Git Bash can parse it. Handles both quoted paths (which may contain
24
+ * spaces, e.g. `node "C:\Program Files\script.js"`) and bare paths
25
+ * (`cd C:\path\x`). Drive letters preceded by another alphanumeric character
26
+ * (e.g. URLs like `http://`) are left untouched.
27
+ */
28
+ export declare function toPosixCommand(command: string): string;
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Windows path conversion utilities for Git Bash (POSIX shell) execution.
3
+ *
4
+ * Hook commands on Windows are executed via Git Bash instead of cmd.exe
5
+ * (cmd.exe does not strip quotes from arguments after the first token, so
6
+ * `node "C:\path\script.js"` silently fails — see issue #1773). Git Bash
7
+ * cannot resolve Windows paths like `C:\Users\foo`: backslashes are treated
8
+ * as escape characters and the drive letter breaks POSIX semantics. These
9
+ * helpers convert Windows paths to the POSIX form Git Bash expects
10
+ * (`C:\Users\foo` → `/c/Users/foo`), matching Claude Code's
11
+ * `windowsPathToPosixPath`.
12
+ */
13
+ /**
14
+ * Convert a single Windows path to POSIX form for Git Bash:
15
+ * - `C:\Users\foo` → `/c/Users/foo`
16
+ * - `C:/Users/foo` → `/c/Users/foo`
17
+ * - `\\server\share` → `//server/share` (UNC preserved)
18
+ * - Already POSIX or relative paths are returned with slashes flipped.
19
+ */
20
+ export function windowsPathToPosixPath(p) {
21
+ // UNC paths: \\server\share -> //server/share
22
+ if (p.startsWith("\\\\")) {
23
+ return p.replace(/\\/g, "/");
24
+ }
25
+ // Drive letter paths: C:\Users\foo -> /c/Users/foo
26
+ const match = p.match(/^([A-Za-z]):[\\/]/);
27
+ if (match) {
28
+ const driveLetter = match[1].toLowerCase();
29
+ return `/${driveLetter}${p.slice(2).replace(/\\/g, "/")}`;
30
+ }
31
+ // Already POSIX or relative — just flip slashes
32
+ return p.replace(/\\/g, "/");
33
+ }
34
+ /**
35
+ * Convert every Windows absolute path inside a shell command string to POSIX
36
+ * form so Git Bash can parse it. Handles both quoted paths (which may contain
37
+ * spaces, e.g. `node "C:\Program Files\script.js"`) and bare paths
38
+ * (`cd C:\path\x`). Drive letters preceded by another alphanumeric character
39
+ * (e.g. URLs like `http://`) are left untouched.
40
+ */
41
+ export function toPosixCommand(command) {
42
+ // Quoted paths first (may contain spaces) — keep the surrounding quotes.
43
+ let converted = command.replace(/"([A-Za-z]):[\\/][^"]*"/g, (quoted) => `"${windowsPathToPosixPath(quoted.slice(1, -1))}"`);
44
+ // Bare (unquoted) paths.
45
+ converted = converted.replace(/(?<![A-Za-z0-9])([A-Za-z]):[\\/][^\s"']*/g, (match) => windowsPathToPosixPath(match));
46
+ return converted;
47
+ }
@@ -22,4 +22,10 @@ export interface WorktreeSession {
22
22
  repoRoot: string;
23
23
  /** The HEAD commit of the original branch at worktree creation time */
24
24
  originalHeadCommit?: string;
25
+ /**
26
+ * True when this worktree was created by a WorktreeCreate hook (not by git).
27
+ * Deletion delegates to the WorktreeRemove hook; wave never runs
28
+ * `git worktree remove` for hook-based worktrees (aligned with Claude Code).
29
+ */
30
+ hookBased?: boolean;
25
31
  }
@@ -41,6 +41,13 @@ export declare function createWorktree(name: string, cwd: string, options?: {
41
41
  export declare function performPostCreationSetup(worktreePath: string, repoRoot: string): Promise<void>;
42
42
  /**
43
43
  * Remove a git worktree and its branch.
44
+ *
45
+ * Removal is best-effort: `git worktree remove --force` deletes the worktree
46
+ * metadata before the working directory, and on Windows its recursive deletion
47
+ * is MAX_PATH-limited — deep paths (e.g. node_modules) can fail with "Filename
48
+ * too long", leaving an orphan directory. When git fails we fall back to
49
+ * fs.rmSync with an extended-length path (bypasses MAX_PATH) and prune stale
50
+ * metadata. Failures are logged but never block branch deletion.
44
51
  */
45
52
  export declare function removeWorktree(info: WorktreeInfo): void;
46
53
  /**
@@ -498,32 +498,77 @@ export async function performPostCreationSetup(worktreePath, repoRoot) {
498
498
  await copyLocalSettingsToWorktree(repoRoot, worktreePath);
499
499
  await copyWorktreeIncludeFiles(repoRoot, worktreePath);
500
500
  }
501
+ /**
502
+ * On Windows, prefix an absolute path with the extended-length marker (`\\?\`)
503
+ * so recursive removal bypasses the 260-char MAX_PATH limit. POSIX paths are
504
+ * returned unchanged.
505
+ */
506
+ function toExtendedLengthPath(worktreePath) {
507
+ if (process.platform !== "win32") {
508
+ return worktreePath;
509
+ }
510
+ const absolute = path.win32.resolve(worktreePath);
511
+ if (absolute.startsWith("\\\\?\\")) {
512
+ return absolute;
513
+ }
514
+ if (absolute.startsWith("\\\\")) {
515
+ // UNC path: \\server\share -> \\?\UNC\server\share
516
+ return `\\\\?\\UNC\\${absolute.slice(2)}`;
517
+ }
518
+ return `\\\\?\\${absolute}`;
519
+ }
501
520
  /**
502
521
  * Remove a git worktree and its branch.
522
+ *
523
+ * Removal is best-effort: `git worktree remove --force` deletes the worktree
524
+ * metadata before the working directory, and on Windows its recursive deletion
525
+ * is MAX_PATH-limited — deep paths (e.g. node_modules) can fail with "Filename
526
+ * too long", leaving an orphan directory. When git fails we fall back to
527
+ * fs.rmSync with an extended-length path (bypasses MAX_PATH) and prune stale
528
+ * metadata. Failures are logged but never block branch deletion.
503
529
  */
504
530
  export function removeWorktree(info) {
505
531
  const repoRoot = info.repoRoot;
532
+ // Get current branch in worktree before removing
533
+ let currentBranch;
534
+ try {
535
+ currentBranch = execFileSync("git", ["rev-parse", "--abbrev-ref", "HEAD"], {
536
+ cwd: info.path,
537
+ encoding: "utf8",
538
+ stdio: ["ignore", "pipe", "ignore"],
539
+ }).trim();
540
+ }
541
+ catch {
542
+ // Ignore errors
543
+ }
544
+ // Remove worktree
506
545
  try {
507
- // Get current branch in worktree before removing
508
- let currentBranch;
509
- try {
510
- currentBranch = execFileSync("git", ["rev-parse", "--abbrev-ref", "HEAD"], {
511
- cwd: info.path,
512
- encoding: "utf8",
513
- stdio: ["ignore", "pipe", "ignore"],
514
- }).trim();
515
- }
516
- catch {
517
- // Ignore errors
518
- }
519
- // Remove worktree
520
546
  execFileSync("git", ["worktree", "remove", "--force", info.path], {
521
547
  cwd: repoRoot,
522
548
  stdio: ["ignore", "pipe", "pipe"],
523
549
  });
524
- // Delete worktree branch
550
+ }
551
+ catch (error) {
552
+ logger.warn("git worktree remove failed, falling back to fs.rmSync:", {
553
+ error: error instanceof Error ? error.message : String(error),
554
+ worktreePath: info.path,
555
+ });
556
+ try {
557
+ fs.rmSync(toExtendedLengthPath(info.path), {
558
+ recursive: true,
559
+ force: true,
560
+ });
561
+ }
562
+ catch (rmError) {
563
+ logger.error("Failed to remove worktree or branch:", {
564
+ error: rmError instanceof Error ? rmError.message : String(rmError),
565
+ worktreePath: info.path,
566
+ });
567
+ }
568
+ // git removes worktree metadata before the working directory; prune any
569
+ // leftovers in case git failed before deleting them.
525
570
  try {
526
- execFileSync("git", ["branch", "-D", info.branch], {
571
+ execFileSync("git", ["worktree", "prune"], {
527
572
  cwd: repoRoot,
528
573
  stdio: ["ignore", "pipe", "pipe"],
529
574
  });
@@ -531,33 +576,36 @@ export function removeWorktree(info) {
531
576
  catch {
532
577
  // Ignore errors
533
578
  }
534
- // Delete current branch if different and not protected
535
- if (currentBranch &&
536
- currentBranch !== info.branch &&
537
- currentBranch !== "HEAD") {
538
- const defaultRemoteBranch = getDefaultRemoteBranch(repoRoot);
539
- const defaultBranchName = defaultRemoteBranch.split("/").pop();
540
- if (currentBranch !== defaultBranchName &&
541
- currentBranch !== "main" &&
542
- currentBranch !== "master") {
543
- try {
544
- execFileSync("git", ["branch", "-D", currentBranch], {
545
- cwd: repoRoot,
546
- stdio: ["ignore", "pipe", "pipe"],
547
- });
548
- }
549
- catch {
550
- // Ignore errors
551
- }
552
- }
553
- }
554
579
  }
555
- catch (error) {
556
- logger.error("Failed to remove worktree or branch:", {
557
- error: error instanceof Error ? error.message : String(error),
558
- worktreePath: info.path,
580
+ // Delete worktree branch
581
+ try {
582
+ execFileSync("git", ["branch", "-D", info.branch], {
583
+ cwd: repoRoot,
584
+ stdio: ["ignore", "pipe", "pipe"],
559
585
  });
560
- throw error;
586
+ }
587
+ catch {
588
+ // Ignore errors
589
+ }
590
+ // Delete current branch if different and not protected
591
+ if (currentBranch &&
592
+ currentBranch !== info.branch &&
593
+ currentBranch !== "HEAD") {
594
+ const defaultRemoteBranch = getDefaultRemoteBranch(repoRoot);
595
+ const defaultBranchName = defaultRemoteBranch.split("/").pop();
596
+ if (currentBranch !== defaultBranchName &&
597
+ currentBranch !== "main" &&
598
+ currentBranch !== "master") {
599
+ try {
600
+ execFileSync("git", ["branch", "-D", currentBranch], {
601
+ cwd: repoRoot,
602
+ stdio: ["ignore", "pipe", "pipe"],
603
+ });
604
+ }
605
+ catch {
606
+ // Ignore errors
607
+ }
608
+ }
561
609
  }
562
610
  }
563
611
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "wave-agent-sdk",
3
- "version": "1.0.10",
3
+ "version": "1.1.0",
4
4
  "description": "SDK for building AI-powered development tools and agents",
5
5
  "keywords": [
6
6
  "ai",
@@ -63,11 +63,10 @@
63
63
  "@vitest/coverage-v8": "^4.1.7",
64
64
  "rimraf": "^6.1.2",
65
65
  "tsc-alias": "^1.8.16",
66
- "tsx": "^4.20.4",
67
66
  "vitest": "^4.1.7"
68
67
  },
69
68
  "engines": {
70
- "node": ">=20"
69
+ "node": ">=22"
71
70
  },
72
71
  "license": "MIT",
73
72
  "scripts": {
@@ -76,6 +75,9 @@
76
75
  "watch": "tsc -p tsconfig.build.json --watch & tsc-alias -p tsconfig.build.json --watch",
77
76
  "test": "vitest run --reporter=dot",
78
77
  "test:coverage": "vitest run --coverage --reporter=dot",
78
+ "test:unit": "vitest run --reporter=dot --exclude 'tests/integration/**' --exclude '**/*.integration.test.ts'",
79
+ "test:unit:coverage": "vitest run --coverage --reporter=dot --exclude 'tests/integration/**' --exclude '**/*.integration.test.ts'",
80
+ "test:integration": "vitest run --reporter=dot tests/integration .integration.test",
79
81
  "lint": "eslint --cache",
80
82
  "format": "prettier --write ."
81
83
  }