@aria-cli/tools 1.0.9 → 1.0.11

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 (241) hide show
  1. package/package.json +9 -5
  2. package/src/__tests__/web-fetch-download.test.ts +0 -433
  3. package/src/__tests__/web-tools.test.ts +0 -619
  4. package/src/ask-user-interaction.ts +0 -33
  5. package/src/cache/web-cache.ts +0 -110
  6. package/src/definitions/arion.ts +0 -118
  7. package/src/definitions/browser/browser.ts +0 -502
  8. package/src/definitions/browser/index.ts +0 -5
  9. package/src/definitions/browser/pw-downloads.ts +0 -142
  10. package/src/definitions/browser/pw-interactions.ts +0 -282
  11. package/src/definitions/browser/pw-responses.ts +0 -98
  12. package/src/definitions/browser/pw-session.ts +0 -405
  13. package/src/definitions/browser/pw-shared.ts +0 -85
  14. package/src/definitions/browser/pw-snapshot.ts +0 -383
  15. package/src/definitions/browser/pw-state.ts +0 -101
  16. package/src/definitions/browser/types.ts +0 -203
  17. package/src/definitions/code-intelligence.ts +0 -526
  18. package/src/definitions/core.ts +0 -118
  19. package/src/definitions/delegation.ts +0 -567
  20. package/src/definitions/deploy.ts +0 -73
  21. package/src/definitions/filesystem.ts +0 -217
  22. package/src/definitions/frg.ts +0 -67
  23. package/src/definitions/index.ts +0 -28
  24. package/src/definitions/memory.ts +0 -150
  25. package/src/definitions/messaging.ts +0 -734
  26. package/src/definitions/meta.ts +0 -392
  27. package/src/definitions/network.ts +0 -179
  28. package/src/definitions/outlook.ts +0 -318
  29. package/src/definitions/patch/apply-patch.ts +0 -235
  30. package/src/definitions/patch/fuzzy-match.ts +0 -217
  31. package/src/definitions/patch/index.ts +0 -1
  32. package/src/definitions/patch/patch-parser.ts +0 -297
  33. package/src/definitions/patch/sandbox-paths.ts +0 -129
  34. package/src/definitions/process/index.ts +0 -5
  35. package/src/definitions/process/process-registry.ts +0 -303
  36. package/src/definitions/process/process.ts +0 -456
  37. package/src/definitions/process/pty-keys.ts +0 -298
  38. package/src/definitions/process/session-slug.ts +0 -147
  39. package/src/definitions/quip.ts +0 -225
  40. package/src/definitions/search.ts +0 -67
  41. package/src/definitions/session-history.ts +0 -79
  42. package/src/definitions/shell.ts +0 -202
  43. package/src/definitions/slack.ts +0 -211
  44. package/src/definitions/web.ts +0 -119
  45. package/src/executors/apply-patch.ts +0 -1035
  46. package/src/executors/arion.ts +0 -199
  47. package/src/executors/code-intelligence.ts +0 -1179
  48. package/src/executors/deploy.ts +0 -1066
  49. package/src/executors/filesystem.ts +0 -1428
  50. package/src/executors/frg-freshness.ts +0 -743
  51. package/src/executors/frg.ts +0 -394
  52. package/src/executors/index.ts +0 -280
  53. package/src/executors/learning-meta.ts +0 -1367
  54. package/src/executors/lsp-client.ts +0 -355
  55. package/src/executors/memory.ts +0 -978
  56. package/src/executors/meta.ts +0 -293
  57. package/src/executors/process-registry.ts +0 -570
  58. package/src/executors/pty-session-store.ts +0 -43
  59. package/src/executors/pty.ts +0 -342
  60. package/src/executors/restart.ts +0 -133
  61. package/src/executors/search-freshness.ts +0 -249
  62. package/src/executors/search-types.ts +0 -98
  63. package/src/executors/search.ts +0 -89
  64. package/src/executors/self-diagnose.ts +0 -552
  65. package/src/executors/session-history.ts +0 -435
  66. package/src/executors/shell-safety.ts +0 -519
  67. package/src/executors/shell.ts +0 -1243
  68. package/src/executors/utils.ts +0 -40
  69. package/src/executors/web.ts +0 -786
  70. package/src/extraction/content-extraction.ts +0 -281
  71. package/src/extraction/index.ts +0 -5
  72. package/src/headless-control-contract.ts +0 -1149
  73. package/src/index.ts +0 -788
  74. package/src/local-control-http-auth.ts +0 -2
  75. package/src/mcp/client.ts +0 -218
  76. package/src/mcp/connection.ts +0 -568
  77. package/src/mcp/index.ts +0 -11
  78. package/src/mcp/jsonrpc.ts +0 -195
  79. package/src/mcp/types.ts +0 -199
  80. package/src/network-control-adapter.ts +0 -88
  81. package/src/network-runtime/address-types.ts +0 -218
  82. package/src/network-runtime/db-owner-fencing.ts +0 -91
  83. package/src/network-runtime/delivery-receipts.ts +0 -372
  84. package/src/network-runtime/direct-endpoint-authority.ts +0 -35
  85. package/src/network-runtime/index.ts +0 -316
  86. package/src/network-runtime/local-control-contract.ts +0 -784
  87. package/src/network-runtime/node-store-contract.ts +0 -46
  88. package/src/network-runtime/pair-route-contract.ts +0 -97
  89. package/src/network-runtime/peer-capabilities.ts +0 -48
  90. package/src/network-runtime/peer-principal-ref.ts +0 -20
  91. package/src/network-runtime/peer-state-machine.ts +0 -160
  92. package/src/network-runtime/protocol-schemas.ts +0 -265
  93. package/src/network-runtime/runtime-bootstrap-contract.ts +0 -83
  94. package/src/outlook/desktop-session.ts +0 -409
  95. package/src/policy.ts +0 -171
  96. package/src/providers/brave.ts +0 -80
  97. package/src/providers/duckduckgo.ts +0 -199
  98. package/src/providers/exa.ts +0 -85
  99. package/src/providers/firecrawl.ts +0 -77
  100. package/src/providers/index.ts +0 -8
  101. package/src/providers/jina.ts +0 -70
  102. package/src/providers/router.ts +0 -121
  103. package/src/providers/search-provider.ts +0 -74
  104. package/src/providers/tavily.ts +0 -74
  105. package/src/quip/desktop-session.ts +0 -435
  106. package/src/registry/index.ts +0 -1
  107. package/src/registry/registry.ts +0 -905
  108. package/src/runtime-socket-local-control-client.ts +0 -632
  109. package/src/security/dns-normalization.ts +0 -34
  110. package/src/security/dns-pinning.ts +0 -138
  111. package/src/security/external-content.ts +0 -129
  112. package/src/security/ssrf.ts +0 -207
  113. package/src/slack/desktop-session.ts +0 -493
  114. package/src/tool-factory.ts +0 -91
  115. package/src/types.ts +0 -1341
  116. package/src/utils/retry.ts +0 -163
  117. package/src/utils/safe-parse-json.ts +0 -176
  118. package/src/utils/url.ts +0 -20
  119. package/tests/benchmarks/registry.bench.ts +0 -57
  120. package/tests/cache/web-cache.test.ts +0 -147
  121. package/tests/critical-integration.test.ts +0 -1465
  122. package/tests/definitions/apply-patch.test.ts +0 -586
  123. package/tests/definitions/browser.test.ts +0 -495
  124. package/tests/definitions/delegation-pause-resume.test.ts +0 -758
  125. package/tests/definitions/execution.test.ts +0 -671
  126. package/tests/definitions/messaging-inbox-scope.test.ts +0 -229
  127. package/tests/definitions/messaging.test.ts +0 -1468
  128. package/tests/definitions/outlook.test.ts +0 -30
  129. package/tests/definitions/process.test.ts +0 -469
  130. package/tests/definitions/slack.test.ts +0 -28
  131. package/tests/definitions/tool-inventory.test.ts +0 -218
  132. package/tests/e2e/delegation-quest-orchestration.e2e.test.ts +0 -433
  133. package/tests/e2e/memory-tool-discovery-contract.e2e.test.ts +0 -81
  134. package/tests/executors/apply-patch.test.ts +0 -538
  135. package/tests/executors/arion.test.ts +0 -309
  136. package/tests/executors/conversation-primitives.test.ts +0 -250
  137. package/tests/executors/deploy.test.ts +0 -746
  138. package/tests/executors/filesystem-tools.test.ts +0 -357
  139. package/tests/executors/filesystem.test.ts +0 -959
  140. package/tests/executors/frg-freshness.test.ts +0 -136
  141. package/tests/executors/frg-merge.test.ts +0 -70
  142. package/tests/executors/frg-session-content.test.ts +0 -40
  143. package/tests/executors/frg.test.ts +0 -56
  144. package/tests/executors/memory-bugfixes.test.ts +0 -257
  145. package/tests/executors/memory-real-memoria.integration.test.ts +0 -316
  146. package/tests/executors/memory.test.ts +0 -853
  147. package/tests/executors/meta-tools.test.ts +0 -411
  148. package/tests/executors/meta.test.ts +0 -683
  149. package/tests/executors/path-containment.test.ts +0 -51
  150. package/tests/executors/process-registry.test.ts +0 -505
  151. package/tests/executors/pty.test.ts +0 -664
  152. package/tests/executors/quest-security.test.ts +0 -249
  153. package/tests/executors/read-file-media.test.ts +0 -230
  154. package/tests/executors/recall-knowledge-schema.test.ts +0 -209
  155. package/tests/executors/recall-tags.test.ts +0 -278
  156. package/tests/executors/remember-null-safety.contract.test.ts +0 -41
  157. package/tests/executors/restart.test.ts +0 -67
  158. package/tests/executors/search-unified.test.ts +0 -381
  159. package/tests/executors/session-history.test.ts +0 -340
  160. package/tests/executors/session-transcript.test.ts +0 -561
  161. package/tests/executors/shell-abort.test.ts +0 -416
  162. package/tests/executors/shell-env-blocklist.test.ts +0 -648
  163. package/tests/executors/shell-env-process.test.ts +0 -245
  164. package/tests/executors/shell-process-registry.test.ts +0 -334
  165. package/tests/executors/shell-tools.test.ts +0 -393
  166. package/tests/executors/shell.test.ts +0 -690
  167. package/tests/executors/web-abort-vs-timeout.test.ts +0 -213
  168. package/tests/executors/web-integration.test.ts +0 -633
  169. package/tests/executors/web-symlink.test.ts +0 -18
  170. package/tests/executors/web.test.ts +0 -1400
  171. package/tests/executors/write-stdin.test.ts +0 -145
  172. package/tests/extraction/content-extraction.test.ts +0 -153
  173. package/tests/guards/tools-default-test-lane.integration.test.ts +0 -21
  174. package/tests/guards/tools-package-test-commands.e2e.test.ts +0 -43
  175. package/tests/guards/tools-test-lane-manifest.contract.test.ts +0 -76
  176. package/tests/guards/tools-vitest-workspace-alias.contract.test.ts +0 -63
  177. package/tests/helpers/async-waits.ts +0 -53
  178. package/tests/integration/headless-control-contract.integration.test.ts +0 -153
  179. package/tests/integration/memory-tool-schema-parity.integration.test.ts +0 -67
  180. package/tests/integration/meta-tools-round-trip.integration.test.ts +0 -506
  181. package/tests/integration/quest-round-trip.test.ts +0 -303
  182. package/tests/integration/registry-executor-flow.test.ts +0 -85
  183. package/tests/integration.test.ts +0 -177
  184. package/tests/loading-tier.test.ts +0 -126
  185. package/tests/mcp/client-reconnect.test.ts +0 -267
  186. package/tests/mcp/connection.test.ts +0 -846
  187. package/tests/mcp/injectable-logger.test.ts +0 -83
  188. package/tests/mcp/jsonrpc.test.ts +0 -109
  189. package/tests/mcp/lifecycle.test.ts +0 -879
  190. package/tests/network-runtime/address-types.contract.test.ts +0 -143
  191. package/tests/network-runtime/continuity-bind-schema.contract.test.ts +0 -203
  192. package/tests/network-runtime/local-control-contract.test.ts +0 -869
  193. package/tests/network-runtime/local-control-invite-token.contract.test.ts +0 -146
  194. package/tests/network-runtime/node-store-contract.test.ts +0 -11
  195. package/tests/network-runtime/pair-protocol-nodeid.contract.test.ts +0 -15
  196. package/tests/network-runtime/peer-state-machine.contract.test.ts +0 -148
  197. package/tests/network-runtime/protocol-schemas.contract.test.ts +0 -512
  198. package/tests/network-runtime/relay-pending-nodeid.contract.test.ts +0 -62
  199. package/tests/network-runtime/runtime-bootstrap-contract.test.ts +0 -227
  200. package/tests/network-runtime/runtime-socket-local-control-client.test.ts +0 -621
  201. package/tests/network-runtime/wait-for-message-script.test.ts +0 -288
  202. package/tests/parallel.test.ts +0 -71
  203. package/tests/policy.test.ts +0 -184
  204. package/tests/print-default-test-lane.ts +0 -14
  205. package/tests/print-test-lane-manifest.ts +0 -22
  206. package/tests/providers/brave.test.ts +0 -159
  207. package/tests/providers/duckduckgo.test.ts +0 -207
  208. package/tests/providers/exa.test.ts +0 -175
  209. package/tests/providers/firecrawl.test.ts +0 -168
  210. package/tests/providers/jina.test.ts +0 -144
  211. package/tests/providers/router.test.ts +0 -328
  212. package/tests/providers/tavily.test.ts +0 -165
  213. package/tests/registry/discovery.test.ts +0 -154
  214. package/tests/registry/injectable-logger.test.ts +0 -230
  215. package/tests/registry/input-validation.test.ts +0 -361
  216. package/tests/registry/interface-completeness.test.ts +0 -85
  217. package/tests/registry/mcp-integration.test.ts +0 -103
  218. package/tests/registry/mcp-read-only-hint.test.ts +0 -60
  219. package/tests/registry/memoria-discovery.test.ts +0 -390
  220. package/tests/registry/nested-validation.test.ts +0 -283
  221. package/tests/registry/pseudo-tool-filtering.test.ts +0 -258
  222. package/tests/registry/registration-lifecycle.test.ts +0 -133
  223. package/tests/registry-validation.test.ts +0 -424
  224. package/tests/registry.test.ts +0 -460
  225. package/tests/security/dns-pinning.test.ts +0 -162
  226. package/tests/security/external-content.test.ts +0 -144
  227. package/tests/security/ssrf.test.ts +0 -118
  228. package/tests/shell-safety-integration.test.ts +0 -32
  229. package/tests/shell-safety.test.ts +0 -365
  230. package/tests/slack/desktop-session.test.ts +0 -50
  231. package/tests/test-lane-manifest.ts +0 -440
  232. package/tests/test-utils.ts +0 -27
  233. package/tests/tool-factory.test.ts +0 -188
  234. package/tests/utils/retry.test.ts +0 -231
  235. package/tests/utils/url.test.ts +0 -63
  236. package/tsconfig.cjs.json +0 -24
  237. package/tsconfig.json +0 -12
  238. package/vitest.config.ts +0 -55
  239. package/vitest.e2e.config.ts +0 -24
  240. package/vitest.integration.config.ts +0 -24
  241. package/vitest.native.config.ts +0 -24
@@ -1,83 +0,0 @@
1
- import { z } from "zod";
2
- import {
3
- LoopbackTlsIdentitySchema,
4
- NodeIdSchema,
5
- OwnerGenerationSchema,
6
- PeerTransportIdSchema,
7
- PrincipalFingerprintSchema,
8
- RuntimeIdSchema,
9
- SigningPublicKeySchema,
10
- TlsCaFingerprintSchema,
11
- TransportEndpointAdvertisementSchema,
12
- } from "./address-types.js";
13
- import { NetworkRuntimeProtocolVersionSchema } from "./protocol-schemas.js";
14
-
15
- const NonEmptyTrimmedStringSchema = z.string().trim().min(1);
16
- const NonBlankVerbatimStringSchema = z
17
- .string()
18
- .min(1)
19
- .refine((value) => value.trim().length > 0);
20
-
21
- export const RuntimeBootstrapRevisionSchema = z.number().int().nonnegative();
22
- export type RuntimeBootstrapRevision = z.infer<typeof RuntimeBootstrapRevisionSchema>;
23
-
24
- export const RuntimeBootstrapPhaseSchema = z.enum([
25
- "starting",
26
- "tls_bound",
27
- "control_ready",
28
- "network_ready",
29
- "mesh_ready",
30
- "degraded",
31
- "stopped",
32
- ]);
33
- export type RuntimeBootstrapPhase = z.infer<typeof RuntimeBootstrapPhaseSchema>;
34
-
35
- export const RuntimeBootstrapControlEndpointSchema = z
36
- .object({
37
- host: NonEmptyTrimmedStringSchema,
38
- port: z.number().int().min(1).max(65535),
39
- })
40
- .strict();
41
- export type RuntimeBootstrapControlEndpoint = z.infer<typeof RuntimeBootstrapControlEndpointSchema>;
42
-
43
- export const RuntimeBootstrapTlsSchema = z
44
- .object({
45
- caFingerprint: TlsCaFingerprintSchema,
46
- caCertPem: NonBlankVerbatimStringSchema,
47
- principalIdentity: PrincipalFingerprintSchema,
48
- loopbackIdentity: LoopbackTlsIdentitySchema,
49
- })
50
- .strict();
51
- export type RuntimeBootstrapTls = z.infer<typeof RuntimeBootstrapTlsSchema>;
52
-
53
- export const RuntimeBootstrapIdentitySchema = z
54
- .object({
55
- signingPublicKey: SigningPublicKeySchema,
56
- transportPublicKey: PeerTransportIdSchema,
57
- transportEndpoint: TransportEndpointAdvertisementSchema,
58
- displayNameSnapshot: NonEmptyTrimmedStringSchema.optional(),
59
- })
60
- .strict();
61
- export type RuntimeBootstrapIdentity = z.infer<typeof RuntimeBootstrapIdentitySchema>;
62
-
63
- export const RuntimeBootstrapRecordSchema = z
64
- .object({
65
- nodeId: NodeIdSchema,
66
- runtimeId: RuntimeIdSchema,
67
- arionName: NonEmptyTrimmedStringSchema.optional(),
68
- ownerGeneration: OwnerGenerationSchema,
69
- bootstrapRevision: RuntimeBootstrapRevisionSchema,
70
- phase: RuntimeBootstrapPhaseSchema,
71
- protocolVersion: NetworkRuntimeProtocolVersionSchema,
72
- controlEndpoint: RuntimeBootstrapControlEndpointSchema,
73
- displayNameSnapshot: NonEmptyTrimmedStringSchema.optional(),
74
- signingPublicKey: SigningPublicKeySchema,
75
- transportPublicKey: PeerTransportIdSchema,
76
- transportEndpoint: TransportEndpointAdvertisementSchema,
77
- tls: RuntimeBootstrapTlsSchema,
78
- publishedAt: NonEmptyTrimmedStringSchema,
79
- degradedReason: NonEmptyTrimmedStringSchema.optional(),
80
- failedPhase: RuntimeBootstrapPhaseSchema.optional(),
81
- })
82
- .strict();
83
- export type RuntimeBootstrapRecord = z.infer<typeof RuntimeBootstrapRecordSchema>;
@@ -1,409 +0,0 @@
1
- import os from "node:os";
2
- import path from "node:path";
3
- import { promises as fs } from "node:fs";
4
-
5
- const OUTLOOK_SESSION_DIR = path.join(os.homedir(), ".aria", "outlook-session");
6
- const OUTLOOK_TOKEN_CACHE = path.join(os.homedir(), ".aria", "cache", "outlook-token.json");
7
- const OUTLOOK_WEB_URL = "https://outlook.office.com/mail/";
8
- // Outlook web uses outlook.office.com-scoped tokens, not graph.microsoft.com.
9
- // The Outlook REST v2 API at outlook.office.com/api/v2.0 accepts these tokens.
10
- const OUTLOOK_REST_API_BASE = "https://outlook.office.com/api/v2.0";
11
- const DEFAULT_BOOTSTRAP_TIMEOUT_MS = 60_000;
12
-
13
- interface CachedToken {
14
- bearerToken: string;
15
- accountEmail: string;
16
- expiresAt: number; // epoch ms
17
- }
18
-
19
- async function loadCachedToken(): Promise<CachedToken | null> {
20
- try {
21
- const raw = await fs.readFile(OUTLOOK_TOKEN_CACHE, "utf-8");
22
- const cached = JSON.parse(raw) as CachedToken;
23
- // Token valid if >5 min remaining
24
- if (cached.bearerToken && cached.expiresAt > Date.now() + 5 * 60_000) {
25
- return cached;
26
- }
27
- } catch {
28
- // no cache or invalid
29
- }
30
- return null;
31
- }
32
-
33
- async function saveCachedToken(token: string, email: string): Promise<void> {
34
- // Decode JWT to get expiry
35
- let exp = Date.now() + 60 * 60_000; // default 1h
36
- try {
37
- const part = token.split(".")[1];
38
- if (!part) throw new Error("no payload");
39
- const payload = JSON.parse(Buffer.from(part, "base64").toString());
40
- if (payload.exp) exp = payload.exp * 1000;
41
- } catch {
42
- /* best-effort */
43
- }
44
- const cached: CachedToken = { bearerToken: token, accountEmail: email, expiresAt: exp };
45
- await fs.mkdir(path.dirname(OUTLOOK_TOKEN_CACHE), { recursive: true });
46
- await fs.writeFile(OUTLOOK_TOKEN_CACHE, JSON.stringify(cached, null, 2));
47
- }
48
-
49
- export interface OutlookMessageView {
50
- id: string;
51
- subject: string;
52
- from: { name: string; email: string };
53
- toRecipients: { name: string; email: string }[];
54
- receivedDateTime: string;
55
- isRead: boolean;
56
- hasAttachments: boolean;
57
- bodyPreview: string;
58
- conversationId: string;
59
- }
60
-
61
- export interface OutlookMessageDetail extends OutlookMessageView {
62
- body: { contentType: string; content: string };
63
- ccRecipients: { name: string; email: string }[];
64
- importance: string;
65
- }
66
-
67
- export interface OutlookListMessagesResult {
68
- accountEmail: string;
69
- folder: string;
70
- messages: OutlookMessageView[];
71
- totalCount: number;
72
- }
73
-
74
- export interface OutlookSendResult {
75
- accountEmail: string;
76
- status: "sent";
77
- }
78
-
79
- export interface OutlookDesktopClient {
80
- getAccountEmail(): string;
81
- listMessages(input: {
82
- folder?: string;
83
- limit?: number;
84
- filter?: string;
85
- search?: string;
86
- }): Promise<OutlookListMessagesResult>;
87
- getMessage(input: { messageId: string }): Promise<OutlookMessageDetail>;
88
- sendMessage(input: {
89
- to: string[];
90
- cc?: string[];
91
- subject: string;
92
- body: string;
93
- bodyType?: "text" | "html";
94
- }): Promise<OutlookSendResult>;
95
- replyMessage(input: {
96
- messageId: string;
97
- body: string;
98
- bodyType?: "text" | "html";
99
- replyAll?: boolean;
100
- }): Promise<OutlookSendResult>;
101
- close(): Promise<void>;
102
- }
103
-
104
- // Outlook REST v2 returns PascalCase keys (Subject, From, EmailAddress)
105
- // while Graph API uses camelCase (subject, from, emailAddress).
106
- // Helper to read a field with either casing.
107
- function field(obj: Record<string, unknown>, camelKey: string): unknown {
108
- if (camelKey in obj) return obj[camelKey];
109
- const pascalKey = camelKey.charAt(0).toUpperCase() + camelKey.slice(1);
110
- return obj[pascalKey];
111
- }
112
-
113
- function fieldStr(obj: Record<string, unknown>, camelKey: string): string {
114
- const v = field(obj, camelKey);
115
- return typeof v === "string" ? v : "";
116
- }
117
-
118
- function parseRecipient(
119
- recipient: Record<string, unknown>,
120
- ): { name: string; email: string } | null {
121
- const emailAddress = (field(recipient, "emailAddress") as Record<string, unknown>) ?? null;
122
- if (!emailAddress || typeof emailAddress !== "object") return null;
123
- return {
124
- name: fieldStr(emailAddress, "name"),
125
- email: fieldStr(emailAddress, "address"),
126
- };
127
- }
128
-
129
- function parseRecipients(raw: unknown): { name: string; email: string }[] {
130
- if (!Array.isArray(raw)) return [];
131
- return raw
132
- .filter((r): r is Record<string, unknown> => !!r && typeof r === "object")
133
- .map(parseRecipient)
134
- .filter((r): r is { name: string; email: string } => r !== null);
135
- }
136
-
137
- function toMessageView(msg: Record<string, unknown>): OutlookMessageView {
138
- const fromRaw = field(msg, "from");
139
- const from =
140
- fromRaw && typeof fromRaw === "object"
141
- ? parseRecipient(fromRaw as Record<string, unknown>)
142
- : null;
143
- return {
144
- id: fieldStr(msg, "id") || fieldStr(msg, "Id"),
145
- subject: fieldStr(msg, "subject"),
146
- from: from ?? { name: "", email: "" },
147
- toRecipients: parseRecipients(field(msg, "toRecipients")),
148
- receivedDateTime: fieldStr(msg, "receivedDateTime"),
149
- isRead: field(msg, "isRead") === true,
150
- hasAttachments: field(msg, "hasAttachments") === true,
151
- bodyPreview: fieldStr(msg, "bodyPreview"),
152
- conversationId: fieldStr(msg, "conversationId"),
153
- };
154
- }
155
-
156
- function toMessageDetail(msg: Record<string, unknown>): OutlookMessageDetail {
157
- const view = toMessageView(msg);
158
- const bodyRaw = field(msg, "body");
159
- const body = bodyRaw && typeof bodyRaw === "object" ? (bodyRaw as Record<string, unknown>) : {};
160
- return {
161
- ...view,
162
- body: {
163
- contentType: fieldStr(body, "contentType") || "text",
164
- content: fieldStr(body, "content"),
165
- },
166
- ccRecipients: parseRecipients(field(msg, "ccRecipients")),
167
- importance: fieldStr(msg, "importance") || "normal",
168
- };
169
- }
170
-
171
- async function waitForMailBearerToken(
172
- page: {
173
- on(
174
- event: "request",
175
- listener: (request: { url(): string; headers(): Record<string, string> }) => void,
176
- ): void;
177
- off(
178
- event: "request",
179
- listener: (request: { url(): string; headers(): Record<string, string> }) => void,
180
- ): void;
181
- },
182
- timeoutMs: number,
183
- ): Promise<{ bearerToken: string; accountEmail: string }> {
184
- return new Promise((resolve, reject) => {
185
- const timer = setTimeout(() => {
186
- page.off("request", handleRequest);
187
- reject(
188
- new Error(
189
- "Timed out waiting for a Mail-scoped bearer token. " +
190
- "Ensure you are logged in to outlook.office.com.",
191
- ),
192
- );
193
- }, timeoutMs);
194
-
195
- const seen = new Set<string>();
196
-
197
- const handleRequest = (request: { url(): string; headers(): Record<string, string> }) => {
198
- const authHeader = request.headers()["authorization"];
199
- if (!authHeader || !authHeader.startsWith("Bearer ")) return;
200
-
201
- const bearerToken = authHeader.slice(7);
202
-
203
- const dedup = bearerToken.substring(0, 30);
204
- if (seen.has(dedup)) return;
205
- seen.add(dedup);
206
-
207
- // Decode JWT payload to extract email and scopes
208
- let accountEmail = "";
209
- let scp = "";
210
- try {
211
- const payloadB64 = bearerToken.split(".")[1];
212
- if (payloadB64) {
213
- const payload = JSON.parse(
214
- Buffer.from(payloadB64, "base64url").toString("utf8"),
215
- ) as Record<string, unknown>;
216
- scp = typeof payload.scp === "string" ? payload.scp : "";
217
- accountEmail =
218
- typeof payload.upn === "string"
219
- ? payload.upn
220
- : typeof payload.preferred_username === "string"
221
- ? payload.preferred_username
222
- : typeof payload.unique_name === "string"
223
- ? payload.unique_name
224
- : "";
225
- }
226
- } catch {
227
- // JWT decode is best-effort
228
- }
229
-
230
- // Only accept tokens with Mail.Read scope (from outlook.cloud.microsoft)
231
- if (!scp.includes("Mail.Read")) return;
232
-
233
- clearTimeout(timer);
234
- page.off("request", handleRequest);
235
- resolve({ bearerToken, accountEmail });
236
- };
237
-
238
- page.on("request", handleRequest);
239
- });
240
- }
241
-
242
- // Stateless client using a cached bearer token (no Playwright needed)
243
- function createStatelessClient(bearerToken: string, accountEmail: string): OutlookDesktopClient {
244
- const invokeApi = async (
245
- method: "GET" | "POST",
246
- endpoint: string,
247
- body?: Record<string, unknown>,
248
- ): Promise<Record<string, unknown>> => {
249
- const url = `${OUTLOOK_REST_API_BASE}${endpoint}`;
250
- const headers: Record<string, string> = {
251
- Authorization: `Bearer ${bearerToken}`,
252
- "Content-Type": "application/json",
253
- };
254
- const resp = await fetch(url, {
255
- method,
256
- headers,
257
- body: body ? JSON.stringify(body) : undefined,
258
- });
259
- if (resp.status === 204) return { status: 204 };
260
- const text = await resp.text();
261
- let json: Record<string, unknown>;
262
- try {
263
- json = JSON.parse(text);
264
- } catch {
265
- throw new Error(`Outlook API ${method} ${endpoint} returned non-JSON (HTTP ${resp.status}).`);
266
- }
267
- if (resp.status >= 400) {
268
- const error =
269
- json.error && typeof json.error === "object" ? (json.error as Record<string, unknown>) : {};
270
- const code = typeof error.code === "string" ? error.code : `http_${resp.status}`;
271
- const message = typeof error.message === "string" ? error.message : "Unknown error";
272
- throw new Error(`Outlook API ${method} ${endpoint} failed: ${code} — ${message}`);
273
- }
274
- return json;
275
- };
276
-
277
- return buildClientMethods(invokeApi, accountEmail, async () => {
278
- /* no-op close */
279
- });
280
- }
281
-
282
- export async function createOutlookDesktopClient(opts?: {
283
- accountHint?: string;
284
- bootstrapTimeoutMs?: number;
285
- }): Promise<OutlookDesktopClient> {
286
- const timeoutMs = opts?.bootstrapTimeoutMs ?? DEFAULT_BOOTSTRAP_TIMEOUT_MS;
287
-
288
- // Strategy 1: Use cached token if still valid (no Playwright needed)
289
- const cached = await loadCachedToken();
290
- if (cached) {
291
- return createStatelessClient(cached.bearerToken, cached.accountEmail);
292
- }
293
-
294
- // Strategy 2: Launch Playwright headful to get a fresh token via SSO
295
- // Must be headful — Microsoft SSO blocks headless Chromium
296
- await fs.mkdir(OUTLOOK_SESSION_DIR, { recursive: true });
297
- const playwright = await import("playwright");
298
- const context = await playwright.chromium.launchPersistentContext(OUTLOOK_SESSION_DIR, {
299
- headless: false,
300
- args: ["--start-maximized"],
301
- viewport: null,
302
- });
303
-
304
- const page = context.pages()[0] ?? (await context.newPage());
305
-
306
- const bootstrapPromise = waitForMailBearerToken(page, timeoutMs);
307
- await page.goto(OUTLOOK_WEB_URL, {
308
- waitUntil: "domcontentloaded",
309
- timeout: timeoutMs,
310
- });
311
-
312
- const { bearerToken, accountEmail } = await bootstrapPromise;
313
-
314
- // Cache the token for subsequent calls (avoids launching Playwright)
315
- await saveCachedToken(bearerToken, accountEmail);
316
-
317
- // Close browser immediately — we have the token, use stateless client
318
- await page.close().catch(() => undefined);
319
- await context.close().catch(() => undefined);
320
-
321
- return createStatelessClient(bearerToken, accountEmail);
322
- }
323
-
324
- type ApiInvoker = (
325
- method: "GET" | "POST",
326
- endpoint: string,
327
- body?: Record<string, unknown>,
328
- ) => Promise<Record<string, unknown>>;
329
-
330
- function buildClientMethods(
331
- invokeApi: ApiInvoker,
332
- accountEmail: string,
333
- closeFn: () => Promise<void>,
334
- ): OutlookDesktopClient {
335
- return {
336
- getAccountEmail: () => accountEmail,
337
-
338
- listMessages: async ({ folder = "inbox", limit = 20, filter, search }) => {
339
- const params = new URLSearchParams();
340
- params.set("$top", String(Math.max(1, Math.min(limit, 50))));
341
- params.set(
342
- "$select",
343
- "Id,Subject,From,ToRecipients,ReceivedDateTime,IsRead,HasAttachments,BodyPreview,ConversationId",
344
- );
345
- params.set("$orderby", "ReceivedDateTime desc");
346
- if (filter) params.set("$filter", filter);
347
- if (search) params.set("$search", `"${search}"`);
348
-
349
- const endpoint = `/me/mailFolders/${encodeURIComponent(folder)}/messages?${params.toString()}`;
350
- const json = await invokeApi("GET", endpoint);
351
-
352
- const rawMessages = Array.isArray(json.value) ? json.value : [];
353
- const messages = rawMessages
354
- .filter((m): m is Record<string, unknown> => !!m && typeof m === "object")
355
- .map(toMessageView);
356
-
357
- return {
358
- accountEmail,
359
- folder,
360
- messages,
361
- totalCount:
362
- typeof json["@odata.count"] === "number" ? json["@odata.count"] : messages.length,
363
- };
364
- },
365
-
366
- getMessage: async ({ messageId }) => {
367
- const json = await invokeApi("GET", `/me/messages/${encodeURIComponent(messageId)}`);
368
- return toMessageDetail(json);
369
- },
370
-
371
- sendMessage: async ({ to, cc, subject, body, bodyType = "text" }) => {
372
- const toRecipients = to.map((email) => ({
373
- EmailAddress: { Address: email },
374
- }));
375
- const ccRecipients = (cc ?? []).map((email) => ({
376
- EmailAddress: { Address: email },
377
- }));
378
-
379
- await invokeApi("POST", "/me/sendMail", {
380
- Message: {
381
- Subject: subject,
382
- Body: { ContentType: bodyType === "html" ? "HTML" : "Text", Content: body },
383
- ToRecipients: toRecipients,
384
- ...(ccRecipients.length > 0 ? { CcRecipients: ccRecipients } : {}),
385
- },
386
- });
387
-
388
- return { accountEmail, status: "sent" as const };
389
- },
390
-
391
- replyMessage: async ({ messageId, body, bodyType = "text", replyAll = false }) => {
392
- const replyMethod = replyAll ? "ReplyAll" : "Reply";
393
- await invokeApi("POST", `/me/messages/${encodeURIComponent(messageId)}/${replyMethod}`, {
394
- Comment: body,
395
- ...(bodyType === "html"
396
- ? {
397
- Message: {
398
- Body: { ContentType: "HTML", Content: body },
399
- },
400
- }
401
- : {}),
402
- });
403
-
404
- return { accountEmail, status: "sent" as const };
405
- },
406
-
407
- close: closeFn,
408
- };
409
- }
package/src/policy.ts DELETED
@@ -1,171 +0,0 @@
1
- /**
2
- * Tool Policy Engine
3
- *
4
- * Evaluates whether a tool is allowed based on allow/deny lists with group expansion.
5
- * Supports layered policy merging (intersection semantics) for arion + RunOptions policies.
6
- */
7
-
8
- export interface ToolPolicy {
9
- /** Tool names or group names to allow. Empty array or undefined = allow all */
10
- allow?: string[];
11
- /** Tool names or group names to deny. Applied after allow. Deny wins. */
12
- deny?: string[];
13
- /**
14
- * Internal marker used by policy merging:
15
- * when true, treat allow (even empty) as an explicit restriction.
16
- * This preserves deny-all semantics for empty intersections.
17
- */
18
- restrictAllow?: boolean;
19
- }
20
-
21
- /** Built-in tool groups */
22
- export const TOOL_GROUPS: Record<string, string[]> = {
23
- "group:memory": [
24
- "remember",
25
- "recall",
26
- "forget",
27
- "recall_knowledge",
28
- "reflect",
29
- "search",
30
- "learn",
31
- "session_history",
32
- ],
33
- "group:web": ["web_search", "web_fetch", "browse", "browser"],
34
- "group:filesystem": ["read_file", "write_file", "edit_file", "glob", "grep", "ls", "apply_patch"],
35
- "group:shell": [
36
- "bash",
37
- "exec",
38
- "spawn",
39
- "kill",
40
- "list_processes",
41
- "wait_process",
42
- "write_stdin",
43
- "process",
44
- ],
45
- "group:arion": [
46
- "hatch_arion",
47
- "wake_arion",
48
- "rest_arion",
49
- "retire_arion",
50
- "delegate_arion",
51
- "manage_network",
52
- "list_clients",
53
- "deploy",
54
- ],
55
- "group:meta": [
56
- "ask_user",
57
- "quest_update",
58
- "quest_list",
59
- "search",
60
- "learn",
61
- "learn_tool",
62
- "learn_skill",
63
- "create_tool",
64
- "create_skill",
65
- "use_skill",
66
- "restart",
67
- "spawn_worker",
68
- "check_delegation",
69
- "pause_delegation",
70
- "resume_delegation",
71
- "quest_report",
72
- "self_diagnose",
73
- ],
74
- };
75
-
76
- /**
77
- * Expand group references in a policy list.
78
- * "group:memory" → ["remember", "recall", "forget", "reflect"]
79
- * Individual tool names pass through unchanged.
80
- * Unknown group names are ignored (treated as empty).
81
- */
82
- export function expandGroups(names: string[]): Set<string> {
83
- const result = new Set<string>();
84
- for (const name of names) {
85
- const lower = name.toLowerCase();
86
- if (lower.startsWith("group:")) {
87
- const members = TOOL_GROUPS[lower];
88
- if (members) {
89
- for (const member of members) {
90
- result.add(member.toLowerCase());
91
- }
92
- }
93
- // Unknown group names are silently ignored
94
- } else {
95
- result.add(lower);
96
- }
97
- }
98
- return result;
99
- }
100
-
101
- /**
102
- * Evaluate whether a tool is allowed by a policy.
103
- * Rules:
104
- * 1. If allow is empty/undefined and restrictAllow is false/undefined
105
- * → all tools allowed (then check deny)
106
- * 2. If allow is non-empty OR restrictAllow=true
107
- * → only listed tools/groups allowed (empty allow + restrictAllow=true denies all)
108
- * 3. Deny always wins over allow
109
- */
110
- export function isToolAllowed(toolName: string, policy: ToolPolicy): boolean {
111
- const normalized = toolName.toLowerCase();
112
-
113
- // Check allow list: when restricted, tool must be in allowed set.
114
- const isAllowRestricted =
115
- policy.restrictAllow === true || (policy.allow !== undefined && policy.allow.length > 0);
116
- if (isAllowRestricted) {
117
- const allowed = expandGroups(policy.allow ?? []);
118
- if (!allowed.has(normalized)) {
119
- return false;
120
- }
121
- }
122
-
123
- // Check deny list: deny always wins
124
- if (policy.deny && policy.deny.length > 0) {
125
- const denied = expandGroups(policy.deny);
126
- if (denied.has(normalized)) {
127
- return false;
128
- }
129
- }
130
-
131
- return true;
132
- }
133
-
134
- /**
135
- * Merge two policies (intersection). Used for layered evaluation:
136
- * arion policy ∩ RunOptions policy = effective policy.
137
- * A tool must be allowed by BOTH layers.
138
- */
139
- export function mergePolicies(a: ToolPolicy, b: ToolPolicy): ToolPolicy {
140
- // Merge deny: union of both deny lists
141
- const mergedDeny = [...(a.deny ?? []), ...(b.deny ?? [])];
142
-
143
- // Merge allow with restriction semantics:
144
- // - both restricted: intersection (possibly empty = deny all)
145
- // - one restricted: inherit that restriction
146
- // - neither restricted: unrestricted
147
- const aRestricts = a.restrictAllow === true || (a.allow?.length ?? 0) > 0;
148
- const bRestricts = b.restrictAllow === true || (b.allow?.length ?? 0) > 0;
149
-
150
- let mergedAllow: string[] | undefined;
151
- let mergedRestrictAllow = false;
152
-
153
- if (aRestricts && bRestricts) {
154
- const expandedA = expandGroups(a.allow ?? []);
155
- const expandedB = expandGroups(b.allow ?? []);
156
- mergedAllow = [...expandedA].filter((name) => expandedB.has(name));
157
- mergedRestrictAllow = true;
158
- } else if (aRestricts) {
159
- mergedAllow = [...(a.allow ?? [])];
160
- mergedRestrictAllow = true;
161
- } else if (bRestricts) {
162
- mergedAllow = [...(b.allow ?? [])];
163
- mergedRestrictAllow = true;
164
- }
165
-
166
- return {
167
- ...(mergedAllow !== undefined ? { allow: mergedAllow } : {}),
168
- ...(mergedRestrictAllow ? { restrictAllow: true } : {}),
169
- ...(mergedDeny.length ? { deny: mergedDeny } : {}),
170
- };
171
- }