@vellumai/assistant 0.4.11 → 0.4.13

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 (111) hide show
  1. package/ARCHITECTURE.md +401 -385
  2. package/package.json +1 -1
  3. package/src/__tests__/guardian-verify-setup-skill-regression.test.ts +75 -61
  4. package/src/__tests__/registry.test.ts +235 -187
  5. package/src/__tests__/secure-keys.test.ts +27 -0
  6. package/src/__tests__/session-agent-loop.test.ts +521 -256
  7. package/src/__tests__/session-surfaces-task-progress.test.ts +1 -0
  8. package/src/__tests__/session-tool-setup-app-refresh.test.ts +1 -0
  9. package/src/__tests__/session-tool-setup-memory-scope.test.ts +1 -0
  10. package/src/__tests__/session-tool-setup-side-effect-flag.test.ts +1 -0
  11. package/src/__tests__/skills.test.ts +334 -276
  12. package/src/__tests__/slack-skill.test.ts +124 -0
  13. package/src/__tests__/starter-task-flow.test.ts +7 -17
  14. package/src/agent/loop.ts +10 -3
  15. package/src/config/bundled-skills/chatgpt-import/tools/chatgpt-import.ts +449 -0
  16. package/src/config/bundled-skills/doordash/SKILL.md +171 -0
  17. package/src/config/bundled-skills/doordash/__tests__/doordash-client.test.ts +203 -0
  18. package/src/config/bundled-skills/doordash/__tests__/doordash-session.test.ts +164 -0
  19. package/src/config/bundled-skills/doordash/doordash-cli.ts +1193 -0
  20. package/src/config/bundled-skills/doordash/doordash-entry.ts +22 -0
  21. package/src/config/bundled-skills/doordash/lib/cart-queries.ts +787 -0
  22. package/src/config/bundled-skills/doordash/lib/client.ts +1071 -0
  23. package/src/config/bundled-skills/doordash/lib/order-queries.ts +85 -0
  24. package/src/config/bundled-skills/doordash/lib/queries.ts +28 -0
  25. package/src/config/bundled-skills/doordash/lib/query-extractor.ts +94 -0
  26. package/src/config/bundled-skills/doordash/lib/search-queries.ts +203 -0
  27. package/src/config/bundled-skills/doordash/lib/session.ts +93 -0
  28. package/src/config/bundled-skills/doordash/lib/shared/errors.ts +61 -0
  29. package/src/config/bundled-skills/doordash/lib/shared/ipc.ts +32 -0
  30. package/src/config/bundled-skills/doordash/lib/shared/network-recorder.ts +380 -0
  31. package/src/config/bundled-skills/doordash/lib/shared/platform.ts +35 -0
  32. package/src/config/bundled-skills/doordash/lib/shared/recording-store.ts +43 -0
  33. package/src/config/bundled-skills/doordash/lib/shared/recording-types.ts +49 -0
  34. package/src/config/bundled-skills/doordash/lib/shared/truncate.ts +6 -0
  35. package/src/config/bundled-skills/doordash/lib/store-queries.ts +246 -0
  36. package/src/config/bundled-skills/doordash/lib/types.ts +367 -0
  37. package/src/config/bundled-skills/google-calendar/SKILL.md +4 -5
  38. package/src/config/bundled-skills/google-oauth-setup/SKILL.md +41 -41
  39. package/src/config/bundled-skills/messaging/SKILL.md +59 -42
  40. package/src/config/bundled-skills/messaging/TOOLS.json +14 -92
  41. package/src/config/bundled-skills/messaging/tools/gmail-archive-by-query.ts +5 -1
  42. package/src/config/bundled-skills/messaging/tools/gmail-batch-archive.ts +11 -2
  43. package/src/config/bundled-skills/messaging/tools/gmail-outreach-scan.ts +8 -1
  44. package/src/config/bundled-skills/messaging/tools/gmail-sender-digest.ts +12 -4
  45. package/src/config/bundled-skills/messaging/tools/gmail-unsubscribe.ts +5 -1
  46. package/src/config/bundled-skills/messaging/tools/messaging-archive-by-sender.ts +5 -1
  47. package/src/config/bundled-skills/messaging/tools/messaging-sender-digest.ts +5 -2
  48. package/src/config/bundled-skills/notion/SKILL.md +240 -0
  49. package/src/config/bundled-skills/notion-oauth-setup/SKILL.md +127 -0
  50. package/src/config/bundled-skills/oauth-setup/SKILL.md +144 -0
  51. package/src/config/bundled-skills/phone-calls/SKILL.md +76 -45
  52. package/src/config/bundled-skills/skills-catalog/SKILL.md +32 -29
  53. package/src/config/bundled-skills/slack/SKILL.md +49 -0
  54. package/src/config/bundled-skills/slack/TOOLS.json +167 -0
  55. package/src/config/bundled-skills/slack/tools/shared.ts +23 -0
  56. package/src/config/bundled-skills/{messaging → slack}/tools/slack-add-reaction.ts +2 -5
  57. package/src/config/bundled-skills/slack/tools/slack-channel-details.ts +33 -0
  58. package/src/config/bundled-skills/slack/tools/slack-configure-channels.ts +75 -0
  59. package/src/config/bundled-skills/{messaging → slack}/tools/slack-delete-message.ts +2 -5
  60. package/src/config/bundled-skills/{messaging → slack}/tools/slack-leave-channel.ts +2 -5
  61. package/src/config/bundled-skills/slack/tools/slack-scan-digest.ts +193 -0
  62. package/src/config/{vellum-skills → bundled-skills}/sms-setup/SKILL.md +29 -22
  63. package/src/config/{vellum-skills → bundled-skills}/telegram-setup/SKILL.md +17 -14
  64. package/src/config/{vellum-skills → bundled-skills}/twilio-setup/SKILL.md +20 -5
  65. package/src/config/bundled-tool-registry.ts +292 -267
  66. package/src/config/schema.ts +1 -1
  67. package/src/daemon/handlers/skills.ts +334 -234
  68. package/src/daemon/ipc-contract/messages.ts +2 -0
  69. package/src/daemon/ipc-contract/surfaces.ts +2 -0
  70. package/src/daemon/lifecycle.ts +358 -221
  71. package/src/daemon/response-tier.ts +2 -0
  72. package/src/daemon/server.ts +453 -193
  73. package/src/daemon/session-agent-loop-handlers.ts +43 -2
  74. package/src/daemon/session-agent-loop.ts +3 -0
  75. package/src/daemon/session-lifecycle.ts +3 -0
  76. package/src/daemon/session-process.ts +1 -0
  77. package/src/daemon/session-surfaces.ts +22 -20
  78. package/src/daemon/session-tool-setup.ts +1 -0
  79. package/src/daemon/session.ts +5 -2
  80. package/src/messaging/outreach-classifier.ts +12 -5
  81. package/src/messaging/provider-types.ts +5 -0
  82. package/src/messaging/provider.ts +1 -1
  83. package/src/messaging/providers/gmail/adapter.ts +11 -5
  84. package/src/messaging/providers/gmail/client.ts +2 -0
  85. package/src/messaging/providers/slack/adapter.ts +1 -0
  86. package/src/messaging/providers/slack/client.ts +8 -0
  87. package/src/messaging/providers/slack/types.ts +5 -0
  88. package/src/runtime/http-errors.ts +33 -20
  89. package/src/runtime/http-server.ts +706 -291
  90. package/src/runtime/http-types.ts +26 -16
  91. package/src/runtime/routes/secret-routes.ts +57 -2
  92. package/src/runtime/routes/surface-action-routes.ts +66 -0
  93. package/src/runtime/routes/trust-rules-routes.ts +140 -0
  94. package/src/security/keychain-to-encrypted-migration.ts +59 -0
  95. package/src/security/secure-keys.ts +17 -0
  96. package/src/skills/frontmatter.ts +9 -7
  97. package/src/tools/apps/executors.ts +2 -1
  98. package/src/tools/tool-manifest.ts +44 -42
  99. package/src/tools/types.ts +9 -0
  100. package/src/__tests__/skill-mirror-parity.test.ts +0 -176
  101. package/src/config/vellum-skills/catalog.json +0 -63
  102. package/src/config/vellum-skills/chatgpt-import/tools/chatgpt-import.ts +0 -295
  103. package/src/skills/vellum-catalog-remote.ts +0 -166
  104. package/src/tools/skills/vellum-catalog.ts +0 -168
  105. /package/src/config/{vellum-skills → bundled-skills}/chatgpt-import/SKILL.md +0 -0
  106. /package/src/config/{vellum-skills → bundled-skills}/chatgpt-import/TOOLS.json +0 -0
  107. /package/src/config/{vellum-skills → bundled-skills}/deploy-fullstack-vercel/SKILL.md +0 -0
  108. /package/src/config/{vellum-skills → bundled-skills}/document-writer/SKILL.md +0 -0
  109. /package/src/config/{vellum-skills → bundled-skills}/guardian-verify-setup/SKILL.md +0 -0
  110. /package/src/config/{vellum-skills → bundled-skills}/slack-oauth-setup/SKILL.md +0 -0
  111. /package/src/config/{vellum-skills → bundled-skills}/trusted-contacts/SKILL.md +0 -0
@@ -0,0 +1,171 @@
1
+ ---
2
+ name: "DoorDash"
3
+ description: "Order food, groceries, and convenience items from DoorDash using the built-in CLI integration"
4
+ user-invocable: true
5
+ metadata:
6
+ {
7
+ "vellum":
8
+ {
9
+ "emoji": "\uD83C\uDF55",
10
+ "cli": { "command": "doordash", "entry": "doordash-entry.ts" },
11
+ },
12
+ }
13
+ ---
14
+
15
+ You can order food from DoorDash for the user using the `doordash` CLI.
16
+
17
+ ## CLI Setup
18
+
19
+ **IMPORTANT: Always use `host_bash` (not `bash`) for all `doordash` commands.** The DoorDash CLI needs host access for Chrome CDP, session cookies, and the CLI binary — none of which are available inside the sandbox.
20
+
21
+ `doordash` is a standalone CLI tool installed at `~/.vellum/bin/doordash`. It should already be on your PATH. If `doordash` is not found, prepend `PATH="$HOME/.vellum/bin:$PATH"` to the command. Do NOT search for the binary, inspect wrapper scripts, or try to discover how the CLI works. Just run the commands as documented below.
22
+
23
+ ## Task Progress Widget
24
+
25
+ A task progress card is shown automatically when you run your first `doordash` command. Its surface ID is `doordash-progress`. As each step completes, call `ui_update` with surface ID `doordash-progress` to update step statuses. Update `data.templateData.steps` — set completed steps to `"status": "completed"` with a `"detail"` string, the current step to `"status": "in_progress"`, and future steps to `"status": "pending"`. Adapt the steps to the actual flow (e.g. skip "Search restaurants" if the user named a specific store).
26
+
27
+ ## Typical Flow
28
+
29
+ When the user asks you to order food (e.g. "Order pizza from Andiamo's"):
30
+
31
+ 1. **Check session** — run `doordash status --json`. If `loggedIn` is false or the session is expired, tell the user: "A Chrome window will open to the DoorDash login page. Please sign in there — I'll detect your login automatically and minimize the window." Then run `doordash refresh --json`. This starts a Ride Shotgun learn session that records your login and auto-stops once it detects you've signed in. The session is imported automatically. **This command blocks until login is complete — just wait for it.**
32
+
33
+ Keep the DoorDash Chrome window open in the background — it's needed for API requests.
34
+
35
+ 2. **Search** — run `doordash search "<query>" --json` to find matching restaurants. Present the top results to the user with name, rating, and delivery info. If the user named a specific restaurant, pick the best match. If ambiguous, ask.
36
+
37
+ 3. **Browse menu** — run `doordash menu <storeId> --json` to get the menu. Show the user the categories and items with prices. If the user already said what they want (e.g. "pepperoni pizza"), find the matching item(s). **For convenience/pharmacy stores** (CVS, Duane Reade, Walgreens etc.), the response will have `isRetail: true` and empty items — use `store-search` instead (see step 3b).
38
+
39
+ 3b. **Search within a retail store** — for convenience/pharmacy stores, run `doordash store-search <storeId> "<query>" --json` to find specific products. This returns items with IDs, prices, and menuIds that can be added to cart directly.
40
+
41
+ 4. **Get item details** (if needed) — run `doordash item <storeId> <itemId> --json` to see options/customizations. The response includes:
42
+ - `options`: each option group has `minSelections`/`maxSelections` indicating how many choices are required
43
+ - Each choice has `unitAmount` (price impact in cents), `defaultQuantity`, and possibly `nestedOptions` (sub-choices like milk type within a size selection)
44
+ - `specialInstructionsConfig`: whether special instructions are accepted, max length, and placeholder text
45
+
46
+ If the item has required options (like size or toppings), construct the `nestedOptions` JSON from the option/choice IDs and pass it via `--options`. Ask the user for preferences or pick sensible defaults.
47
+
48
+ 5. **Add to cart** — run `doordash cart add --store-id <id> --menu-id <id> --item-id <id> --item-name "<name>" --unit-price <cents> [--options '<json>'] [--special-instructions "<text>"] --json`. For subsequent items at the same store, pass `--cart-id <id>` from the first add response. Use `--special-instructions` for requests like "extra hot", "no ice", etc. Use `--options` to pass customization choices (see Customization Options below).
49
+
50
+ 6. **Review cart** — run `doordash cart view <cartId> --json` and show the user what's in their cart with prices. Ask if they want to add anything else or proceed.
51
+
52
+ 7. **Checkout** — run `doordash checkout <cartId> --json` to get delivery options. Present them to the user.
53
+
54
+ 8. **Payment methods** — run `doordash payment-methods --json` to see saved cards. Show the user which card will be used (the default one).
55
+
56
+ 9. **Place order** — after the user explicitly confirms, run `doordash order place --cart-id <id> --store-id <id> --total <cents> [--tip <cents>] [--dropoff-option <id>] --json`. The command auto-selects the default payment method if `--payment-uuid` is not provided. The response contains `orderUuid` on success.
57
+
58
+ ## Important Behavior
59
+
60
+ - **Always confirm before checkout.** Never place an order without explicit user approval.
61
+ - **Be proactive.** If the user says "order pizza from Andiamo's", don't ask clarifying questions upfront — search, find the store, show the menu, and suggest items. Only ask when you need a choice the user hasn't specified.
62
+ - **Handle expired sessions gracefully.** If any command returns `"error": "session_expired"`, run `doordash refresh --json` to re-capture the session.
63
+ - **Show prices.** Always show prices when presenting items or the cart summary.
64
+ - **Use `--json` flag** on all commands for reliable parsing.
65
+ - **Do NOT use the browser skill.** All DoorDash interaction goes through the CLI, not browser automation.
66
+ - **Rate limiting.** DoorDash rate-limits rapid sequential requests. When adding multiple items (e.g. a team order), wait 8–10 seconds between `cart add` calls. If you get a 403 error, wait 15–20 seconds and retry. For large orders (5+ items), consider running `doordash refresh --json` midway through if you hit repeated 403s.
67
+ - **Special instructions are unreliable.** Some merchants disable special instructions entirely. Always prefer `--options` for customizations (size, milk type, etc.). Only use `--special-instructions` for free-text requests that aren't covered by the item's option groups. If the merchant rejects special instructions, drop them and proceed without.
68
+ - **Customization fallback.** If `cart add` with `--options` fails, or if the item details show options that are hard to construct (deeply nested, unusual format), proactively offer to use `cart learn` so the user can customize the item visually in the browser. Don't silently drop customizations — tell the user what happened and offer alternatives.
69
+ - **Always-allow tip.** At the start of an ordering flow, suggest the user enable "always allow" for `doordash` commands: "Tip: You can type 'a' to always allow `doordash` commands for this session so you won't be prompted each time."
70
+ - **Error attribution.** When errors occur, assume it's more likely a bug in our query/parsing than a DoorDash API change. Suggest running `doordash record` to capture fresh queries before assuming the schema changed.
71
+
72
+ ## Customization Options
73
+
74
+ Many items (especially coffee, boba, sandwiches) have required customization options like size, milk type, or toppings. Here's how to handle them:
75
+
76
+ ### Constructing nestedOptions JSON
77
+
78
+ 1. Run `doordash item <storeId> <itemId> --json` to get the item's option groups
79
+ 2. Each option group has `id`, `name`, `required`, `minSelections`, `maxSelections`, and `choices`
80
+ 3. Build a JSON array of selections matching the DoorDash format:
81
+
82
+ ```json
83
+ [
84
+ {
85
+ "optionId": "<option-group-id>",
86
+ "optionChoiceId": "<choice-id>",
87
+ "quantity": 1,
88
+ "nestedOptions": []
89
+ }
90
+ ]
91
+ ```
92
+
93
+ For choices with nested sub-options (e.g., selecting "Oat Milk" under the "Milk" option within a size), add them to the `nestedOptions` array of the parent choice.
94
+
95
+ 4. Pass the JSON string to `cart add --options '<json>'`
96
+
97
+ ### Special Instructions
98
+
99
+ Use `--special-instructions` on `cart add` for free-text requests like "extra hot", "no ice", "light foam". The `item` command response includes `specialInstructionsConfig` with the max length and whether instructions are supported.
100
+
101
+ **Warning:** Some merchants disable special instructions entirely. If `specialInstructionsConfig.isEnabled` is false, or if the add-to-cart call returns an error about special requests, drop the instructions and retry without them. Always prefer `--options` for customizations — special instructions are a last resort for requests not covered by the item's option groups.
102
+
103
+ ### Learning Customizations via Ride Shotgun
104
+
105
+ For complex items where constructing the JSON manually is difficult, use `cart learn`:
106
+
107
+ 1. Run `doordash cart learn --json`
108
+ 2. A Chrome window opens — navigate to the item, customize it visually, and click "Add to Cart"
109
+ 3. The command auto-detects the `updateCartItem` operation and extracts the exact `nestedOptions` and `specialInstructions`
110
+ 4. Use the extracted options directly with `cart add --options '<json>'`
111
+
112
+ You can also extract options from an existing recording with `doordash inspect <recordingId> --extract-options --json`.
113
+
114
+ ### Coffee Order Example
115
+
116
+ **User**: "Order a large oat milk latte with an extra shot from Blue Bottle"
117
+
118
+ 1. `doordash search "Blue Bottle" --json` -> finds store
119
+ 2. `doordash menu <storeId> --json` -> finds "Latte" item
120
+ 3. `doordash item <storeId> <latteItemId> --json` -> returns options:
121
+ - Size (required, min:1, max:1): Small (id:101), Medium (id:102), Large (id:103, +$1.00)
122
+ - Milk (required, min:1, max:1): Whole (id:201), Oat (id:202, +$0.70), Almond (id:203, +$0.70)
123
+ - Extras (optional, min:0, max:5): Extra Shot (id:301, +$0.90), Vanilla Syrup (id:302, +$0.60)
124
+ 4. Construct options JSON and add to cart:
125
+
126
+ ```
127
+ doordash cart add --store-id <id> --menu-id <id> --item-id <id> --item-name "Latte" --unit-price 550 --options '[{"optionId":"size-group-id","optionChoiceId":"103","quantity":1,"nestedOptions":[]},{"optionId":"milk-group-id","optionChoiceId":"202","quantity":1,"nestedOptions":[]},{"optionId":"extras-group-id","optionChoiceId":"301","quantity":1,"nestedOptions":[]}]' --special-instructions "Extra hot" --json
128
+ ```
129
+
130
+ ## Command Reference
131
+
132
+ ```
133
+ doordash status --json # Check if logged in
134
+ doordash refresh --json # Capture fresh session via Ride Shotgun (auto-stops after login)
135
+ doordash login --recording <path> # Import session from a recording file manually
136
+ doordash logout --json # Clear session
137
+ doordash search "<query>" --json # Search restaurants
138
+ doordash menu <storeId> --json # Get store menu (auto-detects retail stores)
139
+ doordash store-search <storeId> "<query>" --json # Search items within a convenience/pharmacy store
140
+ doordash item <storeId> <itemId> --json # Get item details + options
141
+ doordash cart add --store-id <id> --menu-id <id> --item-id <id> --item-name "<name>" --unit-price <cents> [--quantity <n>] [--cart-id <id>] [--options '<json>'] [--special-instructions "<text>"] --json
142
+ doordash cart remove --cart-id <id> --item-id <orderItemId> --json
143
+ doordash cart view <cartId> --json
144
+ doordash cart list [--store-id <id>] --json
145
+ doordash cart learn --json # Learn customization options by recording browser interaction
146
+ doordash inspect <recordingId> --extract-options --json # Extract nestedOptions from a recording
147
+ doordash checkout <cartId> [--address-id <id>] --json
148
+ doordash payment-methods --json # List saved payment methods
149
+ doordash order place --cart-id <id> --store-id <id> --total <cents> [--tip <cents>] [--delivery-option <type>] [--dropoff-option <id>] [--payment-uuid <uuid>] --json
150
+ ```
151
+
152
+ ## Example Interaction
153
+
154
+ **User**: "Order a pepperoni pizza from Andiamo's"
155
+
156
+ 1. `doordash status --json` -> logged in
157
+ 2. `doordash search "Andiamo's" --json` -> finds store 22926474
158
+ 3. `doordash menu 22926474 --json` -> finds "Pepperoni Pizza Pie" (item 2956709006, $28.00)
159
+ 4. Tell user: "I found Pepperoni Pizza Pie at Andiamo's for $28.00. Adding it to your cart."
160
+ 5. `doordash cart add --store-id 22926474 --menu-id 12847574 --item-id 2956709006 --item-name "Pepperoni Pizza Pie" --unit-price 2800 --json`
161
+ 6. `doordash cart view <cartId> --json` -> show summary
162
+ 7. "Your cart has 1x Pepperoni Pizza Pie ($28.00), total $28.00. Ready to check out?"
163
+
164
+ **User**: "I need Tylenol from CVS"
165
+
166
+ 1. `doordash status --json` -> logged in
167
+ 2. `doordash search "CVS" --json` -> finds store 1231787
168
+ 3. `doordash menu 1231787 --json` -> isRetail: true, categories but no items
169
+ 4. `doordash store-search 1231787 "tylenol" --json` -> finds results
170
+ 5. Show top results: "Tylenol Extra Strength Gelcaps (24 ct) - $8.79, Tylenol Extra Strength Caplets (100 ct) - $13.49..."
171
+ 6. User picks one -> add to cart with the item's `id`, `menuId`, and `unitAmount`
@@ -0,0 +1,203 @@
1
+ import { describe, expect, it } from "bun:test";
2
+
3
+ import { SessionExpiredError } from "../lib/client.js";
4
+
5
+ describe("SessionExpiredError", () => {
6
+ it("is an instance of Error", () => {
7
+ const err = new SessionExpiredError("test reason");
8
+ expect(err).toBeInstanceOf(Error);
9
+ });
10
+
11
+ it("has name set to SessionExpiredError", () => {
12
+ const err = new SessionExpiredError("test reason");
13
+ expect(err.name).toBe("SessionExpiredError");
14
+ });
15
+
16
+ it("preserves the reason as the message", () => {
17
+ const err = new SessionExpiredError("DoorDash session has expired.");
18
+ expect(err.message).toBe("DoorDash session has expired.");
19
+ });
20
+
21
+ it("can be distinguished from plain Error via instanceof", () => {
22
+ const sessionErr = new SessionExpiredError("expired");
23
+ const plainErr = new Error("something else");
24
+ expect(sessionErr instanceof SessionExpiredError).toBe(true);
25
+ expect(plainErr instanceof SessionExpiredError).toBe(false);
26
+ });
27
+
28
+ it("produces a useful stack trace", () => {
29
+ const err = new SessionExpiredError("no session");
30
+ expect(err.stack).toBeDefined();
31
+ expect(err.stack).toContain("SessionExpiredError");
32
+ });
33
+ });
34
+
35
+ describe("expired session classification", () => {
36
+ // The CDP response handler in cdpFetch classifies certain HTTP statuses
37
+ // as session-expired. We test the classification logic by simulating
38
+ // the parsed response structure that cdpFetch evaluates.
39
+
40
+ function classifyResponse(parsed: Record<string, unknown>): Error {
41
+ // Mirrors the classification logic from cdpFetch (client.ts lines 154-159)
42
+ if (parsed.__error) {
43
+ if (parsed.__status === 403 || parsed.__status === 401) {
44
+ return new SessionExpiredError("DoorDash session has expired.");
45
+ }
46
+ return new Error(
47
+ (parsed.__message as string) ??
48
+ `HTTP ${parsed.__status}: ${(parsed.__body as string) ?? ""}`,
49
+ );
50
+ }
51
+ return new Error("No error");
52
+ }
53
+
54
+ it("classifies HTTP 401 as SessionExpiredError", () => {
55
+ const err = classifyResponse({
56
+ __error: true,
57
+ __status: 401,
58
+ __body: "Unauthorized",
59
+ });
60
+ expect(err).toBeInstanceOf(SessionExpiredError);
61
+ expect(err.message).toBe("DoorDash session has expired.");
62
+ });
63
+
64
+ it("classifies HTTP 403 as SessionExpiredError", () => {
65
+ const err = classifyResponse({
66
+ __error: true,
67
+ __status: 403,
68
+ __body: "Forbidden",
69
+ });
70
+ expect(err).toBeInstanceOf(SessionExpiredError);
71
+ expect(err.message).toBe("DoorDash session has expired.");
72
+ });
73
+
74
+ it("classifies HTTP 500 as a generic Error, not session expired", () => {
75
+ const err = classifyResponse({
76
+ __error: true,
77
+ __status: 500,
78
+ __body: "Internal Server Error",
79
+ });
80
+ expect(err).not.toBeInstanceOf(SessionExpiredError);
81
+ expect(err.message).toBe("HTTP 500: Internal Server Error");
82
+ });
83
+
84
+ it("classifies HTTP 429 as a generic Error", () => {
85
+ const err = classifyResponse({
86
+ __error: true,
87
+ __status: 429,
88
+ __body: "Rate limited",
89
+ });
90
+ expect(err).not.toBeInstanceOf(SessionExpiredError);
91
+ expect(err.message).toBe("HTTP 429: Rate limited");
92
+ });
93
+
94
+ it("uses __message when available", () => {
95
+ const err = classifyResponse({ __error: true, __message: "fetch failed" });
96
+ expect(err).not.toBeInstanceOf(SessionExpiredError);
97
+ expect(err.message).toBe("fetch failed");
98
+ });
99
+
100
+ it("handles response with no __body or __message gracefully", () => {
101
+ const err = classifyResponse({ __error: true, __status: 502 });
102
+ expect(err).not.toBeInstanceOf(SessionExpiredError);
103
+ expect(err.message).toBe("HTTP 502: ");
104
+ });
105
+ });
106
+
107
+ describe("CDP failure scenarios", () => {
108
+ // These test the error conditions that cdpFetch can encounter:
109
+ // 1. CDP protocol error (msg.error present)
110
+ // 2. Empty CDP response (no value in result)
111
+ // 3. Timeout (30s)
112
+ // 4. WebSocket connection failure
113
+
114
+ // We can test the error construction logic without connecting to a real CDP
115
+
116
+ it("CDP protocol error produces a descriptive message", () => {
117
+ // Simulates the error path at client.ts line 143
118
+ const cdpError = { message: "Cannot find context with specified id" };
119
+ const err = new Error(`CDP error: ${cdpError.message}`);
120
+ expect(err.message).toBe(
121
+ "CDP error: Cannot find context with specified id",
122
+ );
123
+ });
124
+
125
+ it("Empty CDP response produces a clear error", () => {
126
+ // Simulates the error path at client.ts line 149
127
+ const value = undefined;
128
+ const err = !value ? new Error("Empty CDP response") : null;
129
+ expect(err).not.toBeNull();
130
+ expect(err!.message).toBe("Empty CDP response");
131
+ });
132
+
133
+ it("CDP timeout error message includes the timeout duration", () => {
134
+ // Simulates the timeout error at client.ts line 92
135
+ const err = new Error("CDP fetch timed out after 30s");
136
+ expect(err.message).toContain("30s");
137
+ });
138
+
139
+ it("WebSocket connection failure produces SessionExpiredError", () => {
140
+ // Simulates ws.onerror at client.ts line 172
141
+ const err = new SessionExpiredError("CDP connection failed.");
142
+ expect(err).toBeInstanceOf(SessionExpiredError);
143
+ expect(err.message).toBe("CDP connection failed.");
144
+ });
145
+
146
+ it("findDoordashTab failure when CDP is unavailable", () => {
147
+ // Simulates findDoordashTab at client.ts line 67
148
+ const err = new SessionExpiredError(
149
+ "Chrome CDP not available. Run `vellum doordash refresh` first.",
150
+ );
151
+ expect(err).toBeInstanceOf(SessionExpiredError);
152
+ expect(err.message).toContain("Chrome CDP not available");
153
+ });
154
+
155
+ it("findDoordashTab failure when no tab is available", () => {
156
+ // Simulates findDoordashTab at client.ts line 76
157
+ const err = new SessionExpiredError(
158
+ "No Chrome tab available for DoorDash requests.",
159
+ );
160
+ expect(err).toBeInstanceOf(SessionExpiredError);
161
+ expect(err.message).toContain("No Chrome tab available");
162
+ });
163
+
164
+ it("requireSession throws SessionExpiredError when no session exists", () => {
165
+ // Simulates requireSession at client.ts line 56
166
+ const session = null;
167
+ const err = !session
168
+ ? new SessionExpiredError("No DoorDash session found.")
169
+ : null;
170
+ expect(err).toBeInstanceOf(SessionExpiredError);
171
+ expect(err!.message).toBe("No DoorDash session found.");
172
+ });
173
+
174
+ it("GraphQL errors are joined with semicolons", () => {
175
+ // Simulates the error handling at client.ts lines 192-194
176
+ const errors = [
177
+ { message: 'Field "x" not found' },
178
+ { message: "Unauthorized" },
179
+ ];
180
+ const msgs = errors.map((e) => e.message || JSON.stringify(e)).join("; ");
181
+ const err = new Error(`GraphQL errors: ${msgs}`);
182
+ expect(err.message).toBe(
183
+ 'GraphQL errors: Field "x" not found; Unauthorized',
184
+ );
185
+ });
186
+
187
+ it("GraphQL errors use JSON.stringify for errors without message", () => {
188
+ const errors = [{ extensions: { code: "INTERNAL_ERROR" } }];
189
+ const msgs = errors
190
+ .map((e) => (e as Record<string, unknown>).message || JSON.stringify(e))
191
+ .join("; ");
192
+ const err = new Error(`GraphQL errors: ${msgs}`);
193
+ expect(err.message).toContain("INTERNAL_ERROR");
194
+ });
195
+
196
+ it("Empty GraphQL response throws", () => {
197
+ // Simulates client.ts lines 196-198
198
+ const data = undefined;
199
+ const err = !data ? new Error("Empty response from DoorDash API") : null;
200
+ expect(err).not.toBeNull();
201
+ expect(err!.message).toBe("Empty response from DoorDash API");
202
+ });
203
+ });
@@ -0,0 +1,164 @@
1
+ import { existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
2
+ import { tmpdir } from "node:os";
3
+ import { join } from "node:path";
4
+
5
+ import { afterEach, beforeEach, describe, expect, it } from "bun:test";
6
+
7
+ import {
8
+ type DoorDashSession,
9
+ getCookieHeader,
10
+ getCsrfToken,
11
+ importFromRecording,
12
+ } from "../lib/session.js";
13
+
14
+ // Override getDataDir to use a temp directory during tests
15
+ const TEST_DIR = join(tmpdir(), `vellum-dd-test-${process.pid}`);
16
+ let originalDataDir: string | undefined;
17
+
18
+ // We mock getDataDir by patching the module at the fs level:
19
+ // session.ts calls getSessionDir() -> join(getDataDir(), 'doordash')
20
+ // We'll test session.ts helpers that don't depend on getDataDir directly,
21
+ // and test the persistence functions via the actual file system with a known path.
22
+
23
+ function makeCookie(
24
+ name: string,
25
+ value: string,
26
+ ): {
27
+ name: string;
28
+ value: string;
29
+ domain: string;
30
+ path: string;
31
+ httpOnly: boolean;
32
+ secure: boolean;
33
+ } {
34
+ return {
35
+ name,
36
+ value,
37
+ domain: ".doordash.com",
38
+ path: "/",
39
+ httpOnly: false,
40
+ secure: false,
41
+ };
42
+ }
43
+
44
+ function makeSession(overrides?: Partial<DoorDashSession>): DoorDashSession {
45
+ return {
46
+ cookies: [
47
+ makeCookie("dd_session", "abc123"),
48
+ makeCookie("csrf_token", "tok456"),
49
+ ],
50
+ importedAt: "2025-01-15T12:00:00.000Z",
51
+ recordingId: "rec-001",
52
+ ...overrides,
53
+ };
54
+ }
55
+
56
+ describe("DoorDash session helpers", () => {
57
+ describe("getCookieHeader", () => {
58
+ it("joins all cookies into a single header string", () => {
59
+ const session = makeSession();
60
+ const header = getCookieHeader(session);
61
+ expect(header).toBe("dd_session=abc123; csrf_token=tok456");
62
+ });
63
+
64
+ it("returns empty string for a session with no cookies", () => {
65
+ const session = makeSession({ cookies: [] });
66
+ expect(getCookieHeader(session)).toBe("");
67
+ });
68
+
69
+ it("handles a single cookie without trailing semicolons", () => {
70
+ const session = makeSession({ cookies: [makeCookie("a", "1")] });
71
+ expect(getCookieHeader(session)).toBe("a=1");
72
+ });
73
+ });
74
+
75
+ describe("getCsrfToken", () => {
76
+ it("extracts the csrf_token value when present", () => {
77
+ const session = makeSession();
78
+ expect(getCsrfToken(session)).toBe("tok456");
79
+ });
80
+
81
+ it("returns undefined when csrf_token is absent", () => {
82
+ const session = makeSession({
83
+ cookies: [makeCookie("dd_session", "abc123")],
84
+ });
85
+ expect(getCsrfToken(session)).toBeUndefined();
86
+ });
87
+ });
88
+ });
89
+
90
+ describe("DoorDash session persistence", () => {
91
+ // These tests exercise the real loadSession/saveSession/clearSession
92
+ // by writing to the actual session path. We need to mock getDataDir.
93
+ // Since the module uses a private function we can't easily mock,
94
+ // we test via importFromRecording which exercises save+load.
95
+
96
+ beforeEach(() => {
97
+ originalDataDir = process.env.BASE_DATA_DIR;
98
+ process.env.BASE_DATA_DIR = TEST_DIR;
99
+ // Ensure test dir exists
100
+ mkdirSync(TEST_DIR, { recursive: true });
101
+ });
102
+
103
+ afterEach(() => {
104
+ // Restore original BASE_DATA_DIR
105
+ if (originalDataDir === undefined) {
106
+ delete process.env.BASE_DATA_DIR;
107
+ } else {
108
+ process.env.BASE_DATA_DIR = originalDataDir;
109
+ }
110
+ // Clean up test dir
111
+ if (existsSync(TEST_DIR)) {
112
+ rmSync(TEST_DIR, { recursive: true, force: true });
113
+ }
114
+ });
115
+
116
+ describe("importFromRecording", () => {
117
+ it("throws when the recording file does not exist", () => {
118
+ expect(() => importFromRecording("/nonexistent/recording.json")).toThrow(
119
+ "Recording not found",
120
+ );
121
+ });
122
+
123
+ it("throws when the recording contains no cookies", () => {
124
+ const recordingPath = join(TEST_DIR, "empty-recording.json");
125
+ writeFileSync(
126
+ recordingPath,
127
+ JSON.stringify({
128
+ id: "rec-empty",
129
+ startedAt: 0,
130
+ endedAt: 1,
131
+ targetDomain: "doordash.com",
132
+ networkEntries: [],
133
+ cookies: [],
134
+ observations: [],
135
+ }),
136
+ );
137
+ expect(() => importFromRecording(recordingPath)).toThrow(
138
+ "Recording contains no cookies",
139
+ );
140
+ });
141
+
142
+ it("successfully imports a recording with cookies", () => {
143
+ const recordingPath = join(TEST_DIR, "valid-recording.json");
144
+ writeFileSync(
145
+ recordingPath,
146
+ JSON.stringify({
147
+ id: "rec-valid",
148
+ startedAt: 0,
149
+ endedAt: 1,
150
+ targetDomain: "doordash.com",
151
+ networkEntries: [],
152
+ cookies: [makeCookie("session_id", "xyz")],
153
+ observations: [],
154
+ }),
155
+ );
156
+ const session = importFromRecording(recordingPath);
157
+ expect(session.cookies).toHaveLength(1);
158
+ expect(session.cookies[0].name).toBe("session_id");
159
+ expect(session.cookies[0].value).toBe("xyz");
160
+ expect(session.recordingId).toBe("rec-valid");
161
+ expect(session.importedAt).toBeTruthy();
162
+ });
163
+ });
164
+ });