@alpic-ai/api 0.0.0-staging.gbe4a827 → 0.0.0-staging.gbeeddd3

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 (3) hide show
  1. package/dist/index.d.mts +6295 -94
  2. package/dist/index.mjs +910 -227
  3. package/package.json +26 -10
package/dist/index.mjs CHANGED
@@ -2,7 +2,7 @@ import { z } from "zod";
2
2
  import * as z$1 from "zod/v4";
3
3
  import { oc } from "@orpc/contract";
4
4
  import ms from "ms";
5
- //#region ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@4.4.3/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.js
5
+ //#region ../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.32.0_supports-color@7.2.0_zod@4.5.4/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.js
6
6
  /**
7
7
  * Reusable URL validation that disallows javascript: scheme
8
8
  */
@@ -119,7 +119,12 @@ z$1.object({
119
119
  token_type: z$1.string(),
120
120
  expires_in: z$1.coerce.number().optional(),
121
121
  scope: z$1.string().optional(),
122
- refresh_token: z$1.string().optional()
122
+ refresh_token: z$1.string().optional(),
123
+ /**
124
+ * Not part of the wire format: the authorization server this value was obtained from, added by
125
+ * the client's `auth()` before it is stored and compared when it is read back.
126
+ */
127
+ issuer: z$1.string().optional().catch(void 0)
123
128
  }).strip();
124
129
  z$1.object({
125
130
  error: z$1.string(),
@@ -158,7 +163,12 @@ const OAuthClientInformationSchema = z$1.object({
158
163
  client_id: z$1.string(),
159
164
  client_secret: z$1.string().optional(),
160
165
  client_id_issued_at: z$1.number().optional(),
161
- client_secret_expires_at: z$1.number().optional()
166
+ client_secret_expires_at: z$1.number().optional(),
167
+ /**
168
+ * Not part of the wire format: the authorization server this value was obtained from, added by
169
+ * the client's `auth()` before it is stored and compared when it is read back.
170
+ */
171
+ issuer: z$1.string().optional().catch(void 0)
162
172
  }).strip();
163
173
  OAuthClientMetadataSchema.merge(OAuthClientInformationSchema);
164
174
  z$1.object({
@@ -169,11 +179,22 @@ z$1.object({
169
179
  token: z$1.string(),
170
180
  token_type_hint: z$1.string().optional()
171
181
  }).strip();
172
- const platformSchema = z.enum(["chatgpt", "claudeai"]);
182
+ //#endregion
183
+ //#region ../domains/dist/index.mjs
184
+ const AI_PLATFORMS = ["chatgpt", "claudeai"];
185
+ const platformSchema = z.enum(AI_PLATFORMS);
173
186
  const PLATFORM_LABELS = {
174
187
  chatgpt: "ChatGPT",
175
188
  claudeai: "Claude.ai"
176
189
  };
190
+ const WAF_PLATFORMS = [
191
+ "akamai",
192
+ "cato",
193
+ "cloudflare",
194
+ "fastly"
195
+ ];
196
+ const ALLOWED_PLATFORMS = [...AI_PLATFORMS, ...WAF_PLATFORMS];
197
+ const allowedPlatformSchema = z.enum(ALLOWED_PLATFORMS);
177
198
  const auditStatusSchema = z.enum([
178
199
  "pending",
179
200
  "partial",
@@ -246,6 +267,25 @@ z.object({
246
267
  clientSecret: z.string(),
247
268
  clientScopes: z.array(z.string())
248
269
  });
270
+ const creditEntryReasonSchema = z.enum([
271
+ "free_seed",
272
+ "paid_conversion_floor",
273
+ "top_up",
274
+ "usage",
275
+ "admin_adjustment"
276
+ ]);
277
+ z.enum(["playground"]);
278
+ z.number().int().min(500);
279
+ const creditActivityEntrySchema = z.object({
280
+ reason: creditEntryReasonSchema,
281
+ day: z.number(),
282
+ amountInNanoUSD: z.number(),
283
+ messageCount: z.number().nullable()
284
+ });
285
+ z.object({
286
+ balanceInNanoUSD: z.number(),
287
+ recentActivity: z.array(creditActivityEntrySchema)
288
+ });
249
289
  const deploymentStatusSchema$1 = z.enum([
250
290
  "ongoing",
251
291
  "deployed",
@@ -273,34 +313,51 @@ const deploymentSummarySchema = z.object({
273
313
  createdAt: z.coerce.date(),
274
314
  updatedAt: z.coerce.date()
275
315
  });
276
- /**
277
- * Public environment
278
- *
279
- * No OAuth metadata exposed.
280
- */
316
+ /** Public environment: answers anonymously and exposes no OAuth metadata. */
281
317
  const publicEnvironmentSchema = z.object({
318
+ allowsAnonymous: z.literal(true),
319
+ oAuthMetadata: z.strictObject({})
320
+ });
321
+ /** Protected environment whose external resource metadata URL is returned in the WWW-Authenticate header on the first 401; everything after is handled outside the MCP server scope. */
322
+ const externalResourceMetadataEnvironmentSchema = z.object({
323
+ allowsAnonymous: z.boolean(),
324
+ oAuthMetadata: z.object({ externalResourceMetadataUrl: z.url() }),
325
+ scope: z.string().optional()
326
+ });
327
+ /** Protected environment whose own /.well-known/oauth-protected-resource endpoint points at an external authorization server; everything after is handled outside the MCP server scope. */
328
+ const externalAuthorizationServerEnvironmentSchema = z.object({
329
+ allowsAnonymous: z.boolean(),
330
+ oAuthMetadata: z.object({
331
+ externalAuthorizationServerUrl: z.url(),
332
+ resourceMetadata: OAuthProtectedResourceMetadataSchema.optional()
333
+ }),
334
+ scope: z.string().optional()
335
+ });
336
+ /** Standalone protected environment: the server itself exposes both the /.well-known/oauth-protected-resource and /.well-known/oauth-authorization-server endpoints. */
337
+ const standaloneEnvironmentSchema = z.object({
338
+ allowsAnonymous: z.boolean(),
339
+ oAuthMetadata: z.object({
340
+ authorizationServerMetadata: z.union([OAuthMetadataSchema, OpenIdProviderDiscoveryMetadataSchema]),
341
+ resourceMetadata: OAuthProtectedResourceMetadataSchema.optional()
342
+ }),
343
+ scope: z.string().optional()
344
+ });
345
+ /** Protected environment that enforces authentication but advertises no OAuth discovery metadata; clients must obtain credentials out-of-band. */
346
+ const protectedWithoutDiscoveryEnvironmentSchema = z.object({
347
+ allowsAnonymous: z.literal(false),
348
+ oAuthMetadata: z.strictObject({}),
349
+ scope: z.string().optional()
350
+ });
351
+ const legacyPublicEnvironmentSchema = z.object({
282
352
  isPublic: z.literal(true),
283
353
  oAuthMetadata: z.undefined().optional()
284
354
  });
285
- /**
286
- * Protected environment with an external resource metadata URL
287
- *
288
- * An external resource metadata URL is returned in the WWW-Authenticate header during the first 401 response.
289
- * Everything that follows is handled outside of the MCP server scope.
290
- */
291
- const externalResourceMetadataEnvironmentSchema = z.object({
355
+ const legacyExternalResourceMetadataEnvironmentSchema = z.object({
292
356
  isPublic: z.literal(false),
293
357
  oAuthMetadata: z.object({ externalResourceMetadataUrl: z.url() }),
294
358
  scope: z.string().optional()
295
359
  });
296
- /**
297
- * Protected environment with an external authorization server URL
298
- *
299
- * The server itself exposes the /.well-known/oauth-protected-resource endpoint.
300
- * An external authorization server URL is returned when requesting the endpoint.
301
- * Everything that follows is handled outside of the MCP server scope.
302
- */
303
- const externalAuthorizationServerEnvironmentSchema = z.object({
360
+ const legacyExternalAuthorizationServerEnvironmentSchema = z.object({
304
361
  isPublic: z.literal(false),
305
362
  oAuthMetadata: z.object({
306
363
  externalAuthorizationServerUrl: z.url(),
@@ -308,13 +365,7 @@ const externalAuthorizationServerEnvironmentSchema = z.object({
308
365
  }),
309
366
  scope: z.string().optional()
310
367
  });
311
- /**
312
- * Standalone protected environment
313
- *
314
- * The server itself exposes the /.well-known/oauth-protected-resource endpoint.
315
- * The server itself exposes the /.well-known/oauth-authorization-server endpoint.
316
- */
317
- const standaloneEnvironmentSchema = z.object({
368
+ const legacyStandaloneEnvironmentSchema = z.object({
318
369
  isPublic: z.literal(false),
319
370
  oAuthMetadata: z.object({
320
371
  authorizationServerMetadata: z.union([OAuthMetadataSchema, OpenIdProviderDiscoveryMetadataSchema]),
@@ -322,14 +373,7 @@ const standaloneEnvironmentSchema = z.object({
322
373
  }),
323
374
  scope: z.string().optional()
324
375
  });
325
- /**
326
- * Protected environment without OAuth discovery
327
- *
328
- * The server enforces authentication but exposes no OAuth discovery metadata.
329
- * Neither /.well-known/oauth-protected-resource nor /.well-known/oauth-authorization-server
330
- * are advertised. Clients must obtain credentials out-of-band.
331
- */
332
- const protectedWithoutDiscoveryEnvironmentSchema = z.object({
376
+ const legacyProtectedWithoutDiscoveryEnvironmentSchema = z.object({
333
377
  isPublic: z.literal(false),
334
378
  oAuthMetadata: z.strictObject({}),
335
379
  scope: z.string().optional()
@@ -339,9 +383,19 @@ z.union([
339
383
  externalResourceMetadataEnvironmentSchema,
340
384
  externalAuthorizationServerEnvironmentSchema,
341
385
  standaloneEnvironmentSchema,
342
- protectedWithoutDiscoveryEnvironmentSchema
386
+ protectedWithoutDiscoveryEnvironmentSchema,
387
+ legacyPublicEnvironmentSchema,
388
+ legacyExternalResourceMetadataEnvironmentSchema,
389
+ legacyExternalAuthorizationServerEnvironmentSchema,
390
+ legacyStandaloneEnvironmentSchema,
391
+ legacyProtectedWithoutDiscoveryEnvironmentSchema
392
+ ]);
393
+ const playgroundModelSchema = z.enum([
394
+ "global.anthropic.claude-haiku-4-5-20251001-v1:0",
395
+ "global.anthropic.claude-sonnet-4-5-20250929-v1:0",
396
+ "openai.gpt-5.4",
397
+ "openai.gpt-5.5"
343
398
  ]);
344
- const allowedPlatformSchema = platformSchema;
345
399
  const environmentDomainSchema = z.object({
346
400
  name: z.string(),
347
401
  status: z.enum([
@@ -361,6 +415,7 @@ const environmentSchema$1 = z.object({
361
415
  latestDeployment: deploymentSummarySchema.optional(),
362
416
  openaiAppsChallenge: z.string().nullable().optional(),
363
417
  isPlaygroundEnabled: z.boolean(),
418
+ playgroundModel: playgroundModelSchema,
364
419
  isIpWhitelistEnabled: z.boolean(),
365
420
  ipAllowlist: z.array(z.string()).nullable(),
366
421
  allowedPlatforms: z.array(allowedPlatformSchema),
@@ -374,14 +429,17 @@ z.object({
374
429
  collectRequestPayload: z.boolean(),
375
430
  collectResponsePayload: z.boolean(),
376
431
  collectErrorMessage: z.boolean(),
377
- collectUserData: z.boolean()
432
+ collectUserData: z.boolean(),
433
+ identityTraitKey: z.string().min(1).max(200).nullable(),
434
+ leadEventName: z.string().min(1).max(200).nullable()
378
435
  });
379
- z.object({
436
+ const feedbackSchema = z.object({
380
437
  id: z.string(),
381
438
  createdAt: z.coerce.date(),
382
439
  environmentId: z.string(),
383
440
  content: z.string(),
384
- source: z.enum(["model", "user"])
441
+ source: z.enum(["model", "user"]),
442
+ clientName: z.string().nullable()
385
443
  });
386
444
  z.object({
387
445
  content: z.string(),
@@ -397,7 +455,7 @@ const intentCategoryColorSchema = z.enum([
397
455
  "pink",
398
456
  "gray"
399
457
  ]);
400
- intentCategoryColorSchema.options;
458
+ const INTENT_CATEGORY_COLORS = intentCategoryColorSchema.options;
401
459
  const intentCategorySchema = z.object({
402
460
  id: z.string(),
403
461
  createdAt: z.coerce.date(),
@@ -405,7 +463,7 @@ const intentCategorySchema = z.object({
405
463
  name: z.string(),
406
464
  color: intentCategoryColorSchema
407
465
  });
408
- z.object({
466
+ const intentCategorySummarySchema = z.object({
409
467
  id: z.string(),
410
468
  name: z.string(),
411
469
  color: intentCategoryColorSchema,
@@ -417,6 +475,7 @@ z.object({
417
475
  environmentId: z.string(),
418
476
  toolName: z.string(),
419
477
  message: z.string(),
478
+ clientName: z.string().nullable(),
420
479
  categories: z.array(intentCategorySchema)
421
480
  });
422
481
  const signalCategorySchema = z.object({
@@ -475,12 +534,270 @@ z.object({
475
534
  createdAt: z.coerce.date(),
476
535
  updatedAt: z.coerce.date()
477
536
  });
537
+ const alpicMcpRequestLogSchema = z.object({
538
+ type: z.literal("mcp_request"),
539
+ method: z.string()
540
+ });
541
+ const alpicMcpErrorLogSchema = z.object({
542
+ type: z.literal("mcp_error"),
543
+ method: z.string(),
544
+ error: z.string()
545
+ });
546
+ z.union([alpicMcpRequestLogSchema, alpicMcpErrorLogSchema]);
478
547
  z.enum([
479
548
  "INFO",
480
549
  "WARNING",
481
550
  "DEBUG",
482
551
  "ERROR"
483
552
  ]);
553
+ const LOG_SEARCH_MAX_ESCAPED_LENGTH = 960;
554
+ function escapeLogSearchTerm(search) {
555
+ return [...search].flatMap((character) => [...new TextEncoder().encode(character)]).map((byte) => {
556
+ const character = String.fromCharCode(byte);
557
+ return /^[a-zA-Z0-9]$/.test(character) ? character : `\\x${byte.toString(16).toUpperCase().padStart(2, "0")}`;
558
+ }).join("");
559
+ }
560
+ const logSearchSchema = z.string().max(240, `Search must be 240 characters or fewer`).refine((search) => escapeLogSearchTerm(search).length <= LOG_SEARCH_MAX_ESCAPED_LENGTH, "Search is too complex; shorten it or use fewer special characters");
561
+ /** Only names a vendor actually ships belong here: lookalikes like `claude-code-test` are customers' own scripts. */
562
+ const MCP_CLIENT_GROUPS = [
563
+ {
564
+ id: "claude_code",
565
+ label: "Claude Code",
566
+ vendor: "anthropic",
567
+ rawNames: ["claude-code", "Anthropic/ClaudeCodeDesktop"]
568
+ },
569
+ {
570
+ id: "claude",
571
+ label: "Claude",
572
+ vendor: "anthropic",
573
+ rawNames: [
574
+ "Anthropic/ClaudeAI",
575
+ "claude-ai",
576
+ "claude",
577
+ "Claude",
578
+ "claude-desktop",
579
+ "claude-desktop-3p"
580
+ ]
581
+ },
582
+ {
583
+ id: "claude_mobile",
584
+ label: "Claude mobile",
585
+ vendor: "anthropic",
586
+ rawNames: ["claude-ios", "ClaudeAndroid"]
587
+ },
588
+ {
589
+ id: "claude_cowork",
590
+ label: "Claude Cowork",
591
+ vendor: "anthropic",
592
+ rawNames: ["Anthropic/Cowork"]
593
+ },
594
+ {
595
+ id: "claude_toolbox",
596
+ label: "Claude Toolbox",
597
+ vendor: "anthropic",
598
+ rawNames: ["Anthropic/Toolbox", "Anthropic/toolbox-bootstrap"]
599
+ },
600
+ {
601
+ id: "anthropic_api",
602
+ label: "Anthropic API",
603
+ vendor: "anthropic",
604
+ rawNames: ["Anthropic/API"]
605
+ },
606
+ {
607
+ id: "anthropic_connector_refresh",
608
+ label: "Anthropic (connector refresh)",
609
+ vendor: "anthropic",
610
+ rawNames: ["Anthropic"]
611
+ },
612
+ {
613
+ id: "codex",
614
+ label: "Codex",
615
+ vendor: "openai",
616
+ rawNames: [
617
+ "codex-mcp-client",
618
+ "codex",
619
+ "Codex",
620
+ "codex-cli",
621
+ "openai-mcp (Codex)"
622
+ ]
623
+ },
624
+ {
625
+ id: "chatgpt",
626
+ label: "ChatGPT",
627
+ vendor: "openai",
628
+ rawNames: ["openai-mcp (ChatGPT)"]
629
+ },
630
+ {
631
+ id: "openai_responses_api",
632
+ label: "OpenAI Responses API",
633
+ vendor: "openai",
634
+ rawNames: ["openai-mcp (Responses API)"]
635
+ },
636
+ {
637
+ id: "openai_agent_builder",
638
+ label: "OpenAI Agent Builder",
639
+ vendor: "openai",
640
+ rawNames: ["openai-mcp (Agent Builder)"]
641
+ },
642
+ {
643
+ id: "openai_other",
644
+ label: "OpenAI Other",
645
+ vendor: "openai",
646
+ rawNames: ["openai-mcp"]
647
+ },
648
+ {
649
+ id: "cursor",
650
+ label: "Cursor",
651
+ vendor: "cursor",
652
+ rawNames: [
653
+ "cursor-vscode",
654
+ "Cursor",
655
+ "cursor"
656
+ ]
657
+ },
658
+ {
659
+ id: "cline",
660
+ label: "Cline",
661
+ vendor: "cline",
662
+ rawNames: [
663
+ "Cline",
664
+ "cline",
665
+ "@cline/core"
666
+ ]
667
+ },
668
+ {
669
+ id: "github_copilot",
670
+ label: "GitHub Copilot",
671
+ vendor: "githubCopilot",
672
+ rawNames: [
673
+ "Copilot",
674
+ "github-copilot-developer",
675
+ "Copilot MCP Gateway",
676
+ "Xcode/copilot-xcode"
677
+ ]
678
+ },
679
+ {
680
+ id: "gemini_cli",
681
+ label: "Gemini CLI",
682
+ vendor: "google",
683
+ rawNames: ["gemini-cli-mcp-client", "gemini-cli"]
684
+ },
685
+ {
686
+ id: "antigravity",
687
+ label: "Antigravity",
688
+ vendor: "google",
689
+ rawNames: ["antigravity-client"]
690
+ },
691
+ {
692
+ id: "gemini",
693
+ label: "Gemini",
694
+ vendor: "google",
695
+ rawNames: ["Gemini", "google-ai-edge-gallery"]
696
+ },
697
+ {
698
+ id: "windsurf",
699
+ label: "Windsurf",
700
+ vendor: "windsurf",
701
+ rawNames: ["Windsurf", "windsurf-client"]
702
+ },
703
+ {
704
+ id: "mistral",
705
+ label: "Mistral / Le Chat",
706
+ vendor: "mistral",
707
+ rawNames: ["Mistral"],
708
+ rawNamePrefixes: ["connector:custom-mcp:"]
709
+ },
710
+ {
711
+ id: "n8n",
712
+ label: "n8n",
713
+ vendor: "n8n",
714
+ rawNames: [
715
+ "@n8n/n8n-nodes-langchain.mcpClient",
716
+ "@n8n/n8n-nodes-langchain.mcpClientTool",
717
+ "n8n"
718
+ ]
719
+ },
720
+ {
721
+ id: "alpic_playground",
722
+ label: "Alpic Playground",
723
+ vendor: "alpic",
724
+ rawNames: ["alpic-playground", "playground"]
725
+ },
726
+ {
727
+ id: "opencode",
728
+ label: "opencode",
729
+ vendor: "opencode",
730
+ rawNames: ["opencode"]
731
+ },
732
+ {
733
+ id: "zed",
734
+ label: "Zed",
735
+ vendor: "zed",
736
+ rawNames: ["Zed", "zed"]
737
+ },
738
+ {
739
+ id: "zapier",
740
+ label: "Zapier",
741
+ vendor: "zapier",
742
+ rawNames: ["Zapier", "zapier"]
743
+ },
744
+ {
745
+ id: "make",
746
+ label: "Make",
747
+ vendor: "make",
748
+ rawNames: ["Make", "make"]
749
+ },
750
+ {
751
+ id: "librechat",
752
+ label: "LibreChat",
753
+ vendor: "mcp",
754
+ rawNames: ["LibreChat", "librechat"]
755
+ },
756
+ {
757
+ id: "jan",
758
+ label: "Jan",
759
+ vendor: "mcp",
760
+ rawNames: ["Jan", "jan"]
761
+ },
762
+ {
763
+ id: "goose",
764
+ label: "goose",
765
+ vendor: "mcp",
766
+ rawNames: ["goose", "Goose"]
767
+ },
768
+ {
769
+ id: "mcphost",
770
+ label: "mcphost",
771
+ vendor: "mcp",
772
+ rawNames: ["mcphost"]
773
+ },
774
+ {
775
+ id: "mcporter",
776
+ label: "mcporter",
777
+ vendor: "mcp",
778
+ rawNames: ["mcporter"]
779
+ },
780
+ {
781
+ id: "rmcp",
782
+ label: "rmcp",
783
+ vendor: "mcp",
784
+ rawNames: ["rmcp"]
785
+ },
786
+ {
787
+ id: "unnamed_client",
788
+ label: "Unnamed client",
789
+ vendor: "mcp",
790
+ rawNames: [
791
+ "mcp",
792
+ "unknown",
793
+ ""
794
+ ]
795
+ }
796
+ ];
797
+ /** A source pattern, not a RegExp, because analytics renders the same rule into ClickHouse RE2, which shares this syntax. */
798
+ const MCP_REMOTE_WRAPPER_SUFFIX = String.raw` \(via mcp-remote [^\n]+?\)$`;
799
+ new RegExp(MCP_REMOTE_WRAPPER_SUFFIX);
800
+ new Map(MCP_CLIENT_GROUPS.map((group) => [group.id, group]));
484
801
  const runtimeSchema = z.enum([
485
802
  "python3.13",
486
803
  "python3.14",
@@ -515,6 +832,10 @@ const domainFailureReasonSchema = z.enum([
515
832
  "invalid_domain",
516
833
  "other"
517
834
  ]);
835
+ const projectDomainMappingSchema = z.object({
836
+ pathPrefix: z.string(),
837
+ environment: environmentSchema$1
838
+ });
518
839
  z.object({
519
840
  name: z.string(),
520
841
  createdAt: z.coerce.date(),
@@ -524,7 +845,8 @@ z.object({
524
845
  "failed"
525
846
  ]),
526
847
  failureReason: domainFailureReasonSchema.nullable(),
527
- environment: environmentSchema$1
848
+ environment: environmentSchema$1,
849
+ mappings: z.array(projectDomainMappingSchema)
528
850
  });
529
851
  const serverFieldsSchema$1 = z.object({
530
852
  $schema: z.string(),
@@ -553,15 +875,7 @@ z.object({
553
875
  serverFields: serverFieldsSchema$1,
554
876
  source: z.enum(["registry", "defaults"])
555
877
  });
556
- /**
557
- * Returns a variant of a `maxLength`-constrained string that clamps (truncates) instead of
558
- * rejecting on overflow — used for AI-generated copy where the model routinely overshoots.
559
- *
560
- * NOTE: this rebuilds the schema from scratch, carrying over only `maxLength` (as a clamp),
561
- * `minLength`, and the description. Any other validators on the source field (`.regex()`,
562
- * `.email()`, custom refinements) are intentionally dropped — this helper is meant for plain
563
- * free-text length caps only. A field with `null` `maxLength` is returned unchanged.
564
- */
878
+ /** Clamps instead of rejecting on max-length overflow (for AI-generated copy that overshoots); intentionally carries over only maxLength, minLength, and description, dropping any other validators. */
565
879
  const clampStringField = (field) => {
566
880
  const max = field.maxLength;
567
881
  if (max === null) return field;
@@ -569,6 +883,10 @@ const clampStringField = (field) => {
569
883
  const withMin = field.minLength === null ? clamped : clamped.min(field.minLength);
570
884
  return field.description ? withMin.describe(field.description) : withMin;
571
885
  };
886
+ const unboundedArrayField = (field) => {
887
+ const unbounded = z.array(field.element);
888
+ return field.description ? unbounded.describe(field.description) : unbounded;
889
+ };
572
890
  const toolDefinitionSchema = z.object({
573
891
  name: z.string(),
574
892
  title: z.string().optional().describe("Human-friendly name for the tool, used in the UI. If not provided, `name` will be used."),
@@ -581,15 +899,27 @@ const toolDefinitionSchema = z.object({
581
899
  }).optional()
582
900
  });
583
901
  const positiveTestCaseSchema = z.object({
584
- scenario: z.string().describe("Short label for what this case demonstrates."),
585
- userPrompt: z.string().describe("A realistic, standalone user message a reviewer can paste and run with no prior state or multi-turn setup. Vary phrasing and tone across cases."),
902
+ scenario: z.string().min(1).describe("Short label for what this case demonstrates."),
903
+ userPrompt: z.string().min(1).describe("A realistic, standalone user message a reviewer can paste and run with no prior state or multi-turn setup. Vary phrasing and tone across cases."),
586
904
  toolTriggered: z.string().optional().describe("The tool this prompt should invoke."),
587
905
  expectedOutput: z.string().optional().describe("What the user should see, including post-interaction behaviour where relevant.")
588
- }).partial().describe("Each case: Scenario, User prompt, Tool triggered, Expected output.");
906
+ }).describe("Each case: Scenario, User prompt, Tool triggered, Expected output.");
907
+ const positiveTestCaseDraftSchema = positiveTestCaseSchema.partial().extend({
908
+ scenario: z.string().optional(),
909
+ userPrompt: z.string().optional()
910
+ });
911
+ const blankPositiveTestCase = () => ({
912
+ scenario: "",
913
+ userPrompt: "",
914
+ toolTriggered: "",
915
+ expectedOutput: ""
916
+ });
917
+ const toFixedLength = (entries, length, blank) => Array.from({ length }, (_, index) => entries[index] ?? blank());
589
918
  const screenshotEntrySchema = z.object({
590
919
  prompt: z.string(),
591
- url: z.url().or(z.literal(""))
920
+ url: z.url()
592
921
  }).describe("Each screenshot: the user prompt that produced it + the image URL.");
922
+ const screenshotDraftEntrySchema = screenshotEntrySchema.extend({ url: z.string() });
593
923
  /** Accepts either a valid email or URL. */
594
924
  const supportChannelSchema = z.string().refine((value) => z.email().safeParse(value).success || z.url().safeParse(value).success, { error: "Must be a valid email or URL" });
595
925
  /** A URL field whose error spells out that the scheme is required. */
@@ -897,20 +1227,25 @@ const chatgptTranslationLocaleSchema = z.enum([
897
1227
  "zh-TW"
898
1228
  ]);
899
1229
  const negativeTestCaseSchema = z.object({
900
- scenario: z.string(),
901
- userPrompt: z.string()
902
- }).partial().describe("Each case: Scenario + User prompt (the app should NOT trigger).");
1230
+ scenario: z.string().min(1),
1231
+ userPrompt: z.string().min(1)
1232
+ }).describe("Each case: Scenario + User prompt (the plugin should NOT trigger).");
1233
+ const negativeTestCaseDraftSchema = negativeTestCaseSchema.partial().extend({
1234
+ scenario: z.string().optional(),
1235
+ userPrompt: z.string().optional()
1236
+ });
1237
+ const blankNegativeTestCase = () => ({
1238
+ scenario: "",
1239
+ userPrompt: ""
1240
+ });
1241
+ const chatgptSkillSchema = z.object({ name: z.string() }).describe("A skill discovered on the MCP server, by name.");
903
1242
  const chatgptToolJustificationSchema = z.object({
904
1243
  toolName: z.string(),
905
1244
  readOnlyJustification: z.string().describe("One sentence on what the tool reads and returns."),
906
1245
  openWorldJustification: z.string().describe("One sentence on whether the tool reaches external systems beyond your own service."),
907
1246
  destructiveJustification: z.string().describe("One sentence on whether the tool changes data. For a read-only tool, state the full triad: \"No data is created, modified, or deleted.\"")
908
1247
  }).describe("Per-tool justification of each MCP annotation value (one specific sentence per hint).");
909
- /**
910
- * Base copy fields, defined once and reused by both the submission form and per-locale
911
- * translations so the constraints (tagline ≤ 30 chars) never drift. The translation generation
912
- * path wraps these in {@link clampStringField} since the LLM tends to overshoot the limit.
913
- */
1248
+ /** Defined once and reused by both the submission form and per-locale translations so the tagline ≤ 30 chars constraint never drifts. */
914
1249
  const chatgptTaglineSchema = z.string().max(30);
915
1250
  const chatgptDescriptionSchema = z.string();
916
1251
  const chatgptTranslationSchema = z.object({
@@ -919,50 +1254,71 @@ const chatgptTranslationSchema = z.object({
919
1254
  description: chatgptDescriptionSchema
920
1255
  }).describe("Locale-scoped override for tagline + description. English (US) is the default.");
921
1256
  chatgptTranslationSchema.extend({ tagline: clampStringField(chatgptTaglineSchema) });
922
- /**
923
- * Field order mirrors the ChatGPT (OpenAI) submission spreadsheet, grouped by section.
924
- * When adding/removing/reordering fields, keep this in sync with the sheet.
925
- */
1257
+ /** Field order mirrors the ChatGPT (OpenAI) submission spreadsheet, grouped by section; keep it in sync with the sheet. */
926
1258
  const chatgptSubmissionFormDataSchema = z.object({
927
1259
  logoLight: z.string().describe("Logo icon for light mode. Square PNG, no borders or rounded corners (clients apply circular cropping)."),
928
1260
  logoDark: z.string().optional().describe("Optional dark-mode logo icon. Square PNG, same specs as the light icon. Leave empty if the light icon also works on dark backgrounds."),
929
- appName: z.string().describe("The name users will see in ChatGPT and in the Apps Directory."),
1261
+ appName: z.string().describe("The name users will see in ChatGPT and in the Plugin Directory."),
930
1262
  tagline: chatgptTaglineSchema.describe("Plain-language phrase focused on function and user value, 30 chars max. Avoid generic superlatives like \"the best …\"."),
931
- description: chatgptDescriptionSchema.describe("Clear, engaging description highlighting what the app does and why people will love it. Appears publicly on the directory page. End it by naming the product categories or intents the app does NOT cover, so ChatGPT learns when not to route to it (define exclusions by absent categories or wrong intents, never by naming other brands)."),
1263
+ description: chatgptDescriptionSchema.describe("Clear, engaging description highlighting what the plugin does and why people will love it. Appears publicly on the directory page. End it by naming the product categories or intents the plugin does NOT cover, so ChatGPT learns when not to route to it (define exclusions by absent categories or wrong intents, never by naming other brands)."),
932
1264
  category: chatgptCategorySchema.describe("Category from the OpenAI taxonomy."),
933
- developerName: z.string().describe("Developer name shown publicly on the app's directory page."),
1265
+ developerName: z.string().describe("Developer name shown publicly on the plugin's directory page."),
934
1266
  companyUrl: urlField.describe("Your company's main website URL."),
935
1267
  supportChannel: supportChannelSchema.describe("Customer support URL or email address."),
936
1268
  privacyPolicyUrl: urlField.describe("URL to your privacy policy."),
937
- termsOfServiceUrl: urlField.describe("URL to the app's terms of service."),
938
- demoRecordingUrl: urlField.describe("URL to a video demonstrating the app, recorded via OpenAI Developer Mode. Cover all main use cases on web, iOS, and Android."),
939
- appCommerceAndPurchasing: z.boolean().describe("Checkbox: 'My app links or directs users out of ChatGPT to make purchases.' Defaults to false. Verify the app does not offer digital goods."),
1269
+ termsOfServiceUrl: urlField.describe("URL to the plugin's terms of service."),
1270
+ demoRecordingUrl: urlField.describe("URL to a video demonstrating the plugin, recorded via OpenAI Developer Mode. Cover all main use cases on web, iOS, and Android."),
1271
+ appCommerceAndPurchasing: z.boolean().describe("Checkbox: 'My plugin links or directs users out of ChatGPT to make purchases.' Defaults to false. Verify the plugin does not offer digital goods."),
940
1272
  serverUrl: urlField.describe("URL of the MCP server."),
941
1273
  authentication: chatgptAuthenticationSchema.describe("OAuth 2.0 or No auth. OAuth configuration is auto-discovered from the MCP server's metadata."),
942
1274
  tools: z.array(toolDefinitionSchema).describe("List of tools exposed by the MCP server (auto-populated from the production server's manifest)."),
943
1275
  toolJustifications: z.array(chatgptToolJustificationSchema).describe("Per-tool justification of `readOnlyHint`, `openWorldHint`, and `destructiveHint` annotation values. One short, specific sentence per hint describing what the tool actually does."),
944
- testCases: z.array(positiveTestCaseSchema).describe("At least 5 positive test cases. Each: Scenario, User prompt, Tool triggered, Expected output. Collectively cover the full capability across different flow stages (initial search or browse, market or locale handling, post-interaction detail, an action ChatGPT performs on the user's behalf, and a conversion or secondary tool) rather than five variations of the same first step."),
945
- negativeTestCases: z.array(negativeTestCaseSchema).describe("3 negative test cases: prompts where the app should NOT trigger but the model might think it is relevant. These become production routing metadata that teaches ChatGPT when to stay silent, so pick tight near-misses: a product category the app does not carry, the right brand or domain but an intent the app does not serve, or a boundary with a sibling app."),
946
- screenshots: z.array(screenshotEntrySchema.extend({ prompt: z.string().max(75, { error: "Screenshot prompts are limited to 75 characters." }) })).max(3).describe("In-app screenshots paired with the user prompt that produced them (each prompt is 75 characters max). Widget apps must show the widget UI; non-widget apps show the model response. Min 1, max 3 entries, all public. Images: 706px wide, 400–860px tall, PNG."),
1276
+ skills: z.array(chatgptSkillSchema).optional().describe("Skills the server exposes over MCP (auto-populated from the production server's manifest). Left unset when the server does not advertise the skills extension, which is a different state from advertising it and exposing none."),
1277
+ testCases: z.array(positiveTestCaseSchema).length(5).describe("Exactly 5 positive test cases. Each: Scenario, User prompt, Tool triggered, Expected output. Collectively cover the full capability across different flow stages (initial search or browse, market or locale handling, post-interaction detail, an action ChatGPT performs on the user's behalf, and a conversion or secondary tool) rather than five variations of the same first step."),
1278
+ negativeTestCases: z.array(negativeTestCaseSchema).length(3).describe("Exactly 3 negative test cases: prompts where the plugin should NOT trigger but the model might think it is relevant. These become production routing metadata that teaches ChatGPT when to stay silent, so pick tight near-misses: a product category the plugin does not carry, the right brand or domain but an intent the plugin does not serve, or a boundary with a sibling plugin."),
1279
+ screenshots: z.array(screenshotEntrySchema.extend({ prompt: z.string().max(75, { error: "Screenshot prompts are limited to 75 characters." }) })).max(3).describe("In-plugin screenshots paired with the user prompt that produced them (each prompt is 75 characters max). Widget plugins must show the widget UI; non-widget plugins show the model response. Min 1, max 3 entries, all public. Images: 706px wide, 400–860px tall, PNG."),
947
1280
  translations: z.array(chatgptTranslationSchema).describe("Per-locale translation of tagline + description. English (US) is the default."),
948
1281
  allowedCountries: chatgptAllowedCountriesSchema.describe("Availability: all supported countries, or an allow-list / block-list of specific ones (ISO alpha-2)."),
949
- releaseNotes: z.string().describe("Publicly displayed on the app details page.")
1282
+ releaseNotes: z.string().describe("Publicly displayed on the plugin details page.")
1283
+ });
1284
+ const chatgptSubmissionDraftSchema = chatgptSubmissionFormDataSchema.partial().extend({
1285
+ tagline: z.string().optional(),
1286
+ companyUrl: z.string().optional(),
1287
+ supportChannel: z.string().optional(),
1288
+ privacyPolicyUrl: z.string().optional(),
1289
+ termsOfServiceUrl: z.string().optional(),
1290
+ demoRecordingUrl: z.string().optional(),
1291
+ serverUrl: z.string().optional(),
1292
+ screenshots: z.array(screenshotDraftEntrySchema).optional(),
1293
+ testCases: z.array(positiveTestCaseDraftSchema).optional(),
1294
+ negativeTestCases: z.array(negativeTestCaseDraftSchema).optional(),
1295
+ translations: z.array(chatgptTranslationSchema.extend({ tagline: z.string() })).optional()
950
1296
  });
951
- chatgptSubmissionFormDataSchema.pick({
1297
+ /** Source of truth for the fields `SubmissionPrefillService.prefill({ platform: "chatgpt" })` can populate. */
1298
+ const chatgptPrefillFormDataSchema = chatgptSubmissionFormDataSchema.pick({
952
1299
  appName: true,
953
1300
  developerName: true,
954
1301
  serverUrl: true,
955
1302
  tools: true,
1303
+ skills: true,
956
1304
  authentication: true
957
1305
  });
958
- chatgptSubmissionFormDataSchema.pick({
1306
+ /** Source of truth for `SubmissionPrefillService.generate({ platform: "chatgpt" })`. */
1307
+ const chatgptAiGeneratedFormDataSchema = chatgptSubmissionFormDataSchema.pick({
959
1308
  tagline: true,
960
1309
  description: true,
961
1310
  category: true,
962
1311
  testCases: true,
963
1312
  negativeTestCases: true,
964
1313
  toolJustifications: true
965
- }).extend({ tagline: clampStringField(chatgptSubmissionFormDataSchema.shape.tagline) });
1314
+ }).extend({
1315
+ testCases: unboundedArrayField(chatgptSubmissionFormDataSchema.shape.testCases),
1316
+ negativeTestCases: unboundedArrayField(chatgptSubmissionFormDataSchema.shape.negativeTestCases)
1317
+ }).extend({
1318
+ tagline: clampStringField(chatgptSubmissionFormDataSchema.shape.tagline),
1319
+ testCases: z.array(positiveTestCaseDraftSchema).transform((cases) => toFixedLength(cases, 5, blankPositiveTestCase)),
1320
+ negativeTestCases: z.array(negativeTestCaseDraftSchema).transform((cases) => toFixedLength(cases, 3, blankNegativeTestCase))
1321
+ });
966
1322
  const claudeCategorySchema = z.enum([
967
1323
  "Productivity",
968
1324
  "Communication",
@@ -1008,11 +1364,7 @@ const claudePolicyAcknowledgementSchema = z.enum([
1008
1364
  "My connector does not collect conversation data beyond what is needed for its function.",
1009
1365
  "Public documentation for this connector will be live by the publish date."
1010
1366
  ]);
1011
- /**
1012
- * Field order mirrors the claude.ai directory submission wizard
1013
- * (`claude.ai/admin-settings/directory/submissions/new`), grouped by step.
1014
- * When adding/removing/reordering fields, keep this in sync with the wizard.
1015
- */
1367
+ /** Field order mirrors the claude.ai directory submission wizard (`claude.ai/admin-settings/directory/submissions/new`), grouped by step; keep it in sync with the wizard. */
1016
1368
  const claudeSubmissionFormDataSchema = z.object({
1017
1369
  serverUrl: z.url().describe(`The full https:// URL where your MCP server is hosted and reachable. In the claude.ai wizard this is read live
1018
1370
  from the custom connector you select — the connection is used to verify the URL and the tool list at submission time.
@@ -1074,7 +1426,23 @@ fully populated account.`),
1074
1426
  submission. Each is an attestation you are legally agreeing to by submitting.`),
1075
1427
  additionalNotes: z.string().optional().describe("Anything else the review team should know about your connector. Optional.")
1076
1428
  });
1077
- claudeSubmissionFormDataSchema.pick({
1429
+ const claudeSubmissionDraftSchema = claudeSubmissionFormDataSchema.partial().extend({
1430
+ serverUrl: z.string().optional(),
1431
+ name: z.string().optional(),
1432
+ slug: z.string().optional(),
1433
+ oneLiner: z.string().optional(),
1434
+ description: z.string().optional(),
1435
+ iconUrl: z.string().optional(),
1436
+ documentation: z.string().optional(),
1437
+ support: z.string().optional(),
1438
+ privacyPolicy: z.string().optional(),
1439
+ companyWebsite: z.string().optional(),
1440
+ primaryContactEmail: z.string().optional(),
1441
+ categories: z.array(claudeCategorySchema).optional(),
1442
+ screenshots: z.array(screenshotDraftEntrySchema).optional()
1443
+ });
1444
+ /** Source of truth for the fields `SubmissionPrefillService.prefill({ platform: "claudeai" })` can populate. */
1445
+ const claudePrefillFormDataSchema = claudeSubmissionFormDataSchema.pick({
1078
1446
  serverUrl: true,
1079
1447
  name: true,
1080
1448
  slug: true,
@@ -1089,39 +1457,93 @@ claudeSubmissionFormDataSchema.pick({
1089
1457
  connectionRequirements: claudeSubmissionFormDataSchema.shape.connectionRequirements.optional(),
1090
1458
  testInstructions: claudeSubmissionFormDataSchema.shape.testInstructions.optional()
1091
1459
  });
1092
- /**
1093
- * Narrative fields the LLM-backed generation step produces for Claude submissions.
1094
- * This schema accepts the slightly loose shape returned by AI generation, then normalizes it into
1095
- * the strict form shape. Keep transforms here rather than in callers so generation leniency is
1096
- * colocated with the Claude contract.
1097
- */
1460
+ /** Loose shape returned by AI generation for Claude narrative fields; transforms live here so generation leniency stays colocated with the Claude contract. */
1098
1461
  const claudeAiGeneratedFormDataRawSchema = z.object({
1099
1462
  oneLiner: claudeSubmissionFormDataSchema.shape.oneLiner,
1100
1463
  description: claudeSubmissionFormDataSchema.shape.description,
1101
1464
  categories: z.array(claudeCategorySchema).describe(claudeCategoryDescription),
1102
1465
  primaryUseCases: claudeSubmissionFormDataSchema.shape.primaryUseCases
1103
1466
  });
1104
- claudeAiGeneratedFormDataRawSchema.extend({
1467
+ const claudeAiGeneratedFormDataSchema = claudeAiGeneratedFormDataRawSchema.extend({
1105
1468
  oneLiner: clampStringField(claudeSubmissionFormDataSchema.shape.oneLiner),
1106
1469
  categories: claudeAiGeneratedFormDataRawSchema.shape.categories.transform((categories) => categories.slice(0, 5))
1107
1470
  });
1471
+ function provenanceByField(prefillShape, aiGeneratedShape) {
1472
+ const byField = {};
1473
+ for (const field of Object.keys(prefillShape)) byField[field] = "prefilled";
1474
+ for (const field of Object.keys(aiGeneratedShape)) byField[field] = "ai-generated";
1475
+ return byField;
1476
+ }
1477
+ provenanceByField(claudePrefillFormDataSchema.shape, claudeAiGeneratedFormDataSchema.shape), provenanceByField(chatgptPrefillFormDataSchema.shape, chatgptAiGeneratedFormDataSchema.shape);
1478
+ const urlVerificationOutcomeSchema = z.enum([
1479
+ "pass",
1480
+ "fail",
1481
+ "unverified"
1482
+ ]);
1483
+ const VERIFIABLE_URL_FIELDS = {
1484
+ chatgpt: ["privacyPolicyUrl", "termsOfServiceUrl"],
1485
+ claudeai: ["privacyPolicy"]
1486
+ };
1487
+ const verifiableUrlFieldSchema = z.enum([...VERIFIABLE_URL_FIELDS.chatgpt, ...VERIFIABLE_URL_FIELDS.claudeai]);
1488
+ const policyDisclosureSchema = z.enum([
1489
+ "dataCategories",
1490
+ "purposesOfUse",
1491
+ "recipients",
1492
+ "retention"
1493
+ ]);
1494
+ const urlVerificationFieldResultSchema = z.object({
1495
+ field: verifiableUrlFieldSchema,
1496
+ url: z.string(),
1497
+ outcome: urlVerificationOutcomeSchema,
1498
+ reason: z.string(),
1499
+ concerns: z.array(z.string()).optional(),
1500
+ scrapedWith: z.enum(["fetch", "firecrawl"]).optional()
1501
+ });
1502
+ const urlVerificationSchema = z.object({
1503
+ verifiedAt: z.coerce.date(),
1504
+ results: z.array(urlVerificationFieldResultSchema)
1505
+ });
1506
+ const pageKindSchema = z.enum([
1507
+ "expectedDocument",
1508
+ "errorPage",
1509
+ "loginWall",
1510
+ "parkedDomain",
1511
+ "comingSoon",
1512
+ "marketingPage",
1513
+ "unrelatedDocument"
1514
+ ]);
1515
+ z.object({
1516
+ pageKind: pageKindSchema.describe("What the page actually is. Use 'expectedDocument' only when it is genuinely the document the field claims."),
1517
+ reason: z.string().max(200).describe("One sentence naming what the page is, addressed to the developer who entered the URL."),
1518
+ missingDisclosures: z.array(policyDisclosureSchema).describe("For a privacy policy only: which of the four required disclosures the text does not cover. Empty for every other page kind.")
1519
+ });
1108
1520
  const submissionMetaFieldsSchema = z.object({
1109
1521
  id: z.string(),
1110
1522
  environmentId: z.string(),
1111
1523
  auditId: z.string().nullable(),
1524
+ urlVerification: urlVerificationSchema.nullable().default(null),
1112
1525
  createdAt: z.coerce.date(),
1113
1526
  updatedAt: z.coerce.date()
1114
1527
  });
1115
1528
  const claudeSubmissionSchemaInternal = submissionMetaFieldsSchema.extend({
1116
1529
  platform: z.literal("claudeai"),
1117
- formData: claudeSubmissionFormDataSchema.partial()
1530
+ formData: claudeSubmissionDraftSchema,
1531
+ prefillSnapshot: claudeSubmissionDraftSchema.nullable().default(null)
1118
1532
  });
1119
1533
  const chatgptSubmissionSchemaInternal = submissionMetaFieldsSchema.extend({
1120
1534
  platform: z.literal("chatgpt"),
1121
- formData: chatgptSubmissionFormDataSchema.partial()
1535
+ formData: chatgptSubmissionDraftSchema,
1536
+ prefillSnapshot: chatgptSubmissionDraftSchema.nullable().default(null)
1122
1537
  });
1123
- z.discriminatedUnion("platform", [claudeSubmissionSchemaInternal, chatgptSubmissionSchemaInternal]);
1124
- z.union([claudeSubmissionFormDataSchema.partial(), chatgptSubmissionFormDataSchema.partial()]);
1538
+ const submissionSchemaInternal = z.discriminatedUnion("platform", [claudeSubmissionSchemaInternal, chatgptSubmissionSchemaInternal]);
1539
+ z.union([claudeSubmissionDraftSchema, chatgptSubmissionDraftSchema]);
1540
+ /** Discriminated on `platform`, which pins the shape of `formData`: a Claude submission cannot carry chatgpt-only fields, and vice-versa. */
1541
+ const submissionSchema = submissionSchemaInternal;
1542
+ z.literal([
1543
+ 100,
1544
+ 75,
1545
+ 50
1546
+ ]);
1125
1547
  const subscriptionPlanSchema = z.enum([
1126
1548
  "pro",
1127
1549
  "business",
@@ -1133,17 +1555,71 @@ const customerCreditsSchema = z.object({
1133
1555
  expiresAt: z.number().nullable(),
1134
1556
  currency: z.string()
1135
1557
  });
1136
- const customerUsageSchema = z.object({
1137
- amountInCents: z.number(),
1138
- currency: z.string(),
1139
- periodEnd: z.number()
1140
- });
1141
1558
  const partnerDiscountSchema = z.object({ endsAt: z.number() });
1142
1559
  z.object({
1143
1560
  customerCredits: customerCreditsSchema.nullable(),
1144
- customerUsage: customerUsageSchema.nullable(),
1145
1561
  partnerDiscount: partnerDiscountSchema.nullable()
1146
1562
  });
1563
+ const metricsQueueEventSchema = z.object({
1564
+ ts: z.number().int(),
1565
+ method: z.string(),
1566
+ tool: z.string().nullable(),
1567
+ client: z.string(),
1568
+ sessionId: z.string().nullable(),
1569
+ durationMs: z.number().int(),
1570
+ outputTokens: z.number().int().nullable(),
1571
+ errorType: z.enum([
1572
+ "mcp_error",
1573
+ "tool_error",
1574
+ "timeout"
1575
+ ]).nullable(),
1576
+ errorCode: z.number().int().nullable()
1577
+ });
1578
+ z.object({
1579
+ v: z.literal(1),
1580
+ envId: z.string(),
1581
+ events: z.array(metricsQueueEventSchema)
1582
+ });
1583
+ z.object({ v: z.number() });
1584
+ const telemetrySignalSchema = z.enum([
1585
+ "logs",
1586
+ "metrics",
1587
+ "traces"
1588
+ ]);
1589
+ const otlpProtocolSchema = z.enum(["http/protobuf", "http/json"]);
1590
+ const otlpEndpointSchema = z.string().trim().min(1).max(2048);
1591
+ const OTLP_HEADER_VALUE_MAX_LENGTH = 2048;
1592
+ const otlpHeaderNameSchema = z.string().trim().min(1, "Enter a header name").max(128).regex(/^[A-Za-z0-9!#$%&'*+\-.^_`|~]+$/, "Use letters, digits and !#$%&'*+-.^_`|~ only");
1593
+ const otlpHeaderValueSchema = z.string().trim().max(OTLP_HEADER_VALUE_MAX_LENGTH).refine((value) => !/[\r\n]/.test(value), "Line breaks are not allowed in a header value");
1594
+ const telemetryDestinationHeaderSchema = z.object({
1595
+ id: z.string(),
1596
+ name: otlpHeaderNameSchema,
1597
+ value: otlpHeaderValueSchema,
1598
+ isSecret: z.boolean()
1599
+ });
1600
+ const otlpPushFailureReasonSchema = z.enum([
1601
+ "credentials",
1602
+ "wrong-path",
1603
+ "wrong-protocol",
1604
+ "invalid-payload",
1605
+ "partial-rejection",
1606
+ "blocked-target",
1607
+ "timeout",
1608
+ "unreachable",
1609
+ "receiver-error",
1610
+ "unexpected-status"
1611
+ ]);
1612
+ const telemetryDestinationStatusSchema = z.enum(["active", "suspended"]);
1613
+ z.object({
1614
+ id: z.string(),
1615
+ signal: telemetrySignalSchema,
1616
+ endpoint: otlpEndpointSchema,
1617
+ protocol: otlpProtocolSchema,
1618
+ headers: z.array(telemetryDestinationHeaderSchema),
1619
+ status: telemetryDestinationStatusSchema,
1620
+ lastFailureReason: otlpPushFailureReasonSchema.nullable(),
1621
+ isScopedToIntentionalRequestsOnly: z.boolean()
1622
+ });
1147
1623
  //#endregion
1148
1624
  //#region src/auth-scope.ts
1149
1625
  /** Accepts an API key or OAuth access token (default for most routes). */
@@ -1186,7 +1662,10 @@ const RESERVED_KEYS = [
1186
1662
  "BUILD_ARG_START_COMMAND",
1187
1663
  "ALPIC_HOST",
1188
1664
  "ALPIC_CUSTOM_DOMAINS",
1189
- "ALPIC_INTENT_META_KEY"
1665
+ "ALPIC_INTENT_META_KEY",
1666
+ "ALPIC_FEEDBACK_META_KEY",
1667
+ "ALPIC_EVENTS_META_KEY",
1668
+ "ALPIC_IDENTIFY_META_KEY"
1190
1669
  ];
1191
1670
  const environmentVariableSchema = z.object({
1192
1671
  key: z.string().min(2, "Key must be at least 2 characters").regex(/^[a-zA-Z]([a-zA-Z0-9_])+$/, "Key must start with a letter and contain only letters, numbers, and underscores").refine((key) => !RESERVED_KEYS.includes(key), "This key is reserved and cannot be used as an environment variable key"),
@@ -1239,6 +1718,14 @@ const serverFieldsSchema = z.object({
1239
1718
  });
1240
1719
  //#endregion
1241
1720
  //#region src/api.contract.ts
1721
+ const isValidIanaTimeZone = (timeZone) => {
1722
+ try {
1723
+ new Intl.DateTimeFormat("en-US", { timeZone });
1724
+ return true;
1725
+ } catch {
1726
+ return false;
1727
+ }
1728
+ };
1242
1729
  const deploymentStatusSchema = z.enum([
1243
1730
  "ongoing",
1244
1731
  "deployed",
@@ -1267,21 +1754,20 @@ const deploymentSchema = z.object({
1267
1754
  isCurrent: z.boolean(),
1268
1755
  deploymentPageUrl: z.url().nullable()
1269
1756
  });
1270
- const isValidLogTimeInput = (value) => {
1757
+ const isValidTimeInput = (value) => {
1271
1758
  if (ms(value) !== void 0) return true;
1272
1759
  return !Number.isNaN(new Date(value).getTime());
1273
1760
  };
1274
- const createEnvironmentContractV1 = oc.route({
1761
+ const timeInputSchema = z.string().refine(isValidTimeInput, { message: "Invalid time. Use relative (1h, 30m, 2d) or ISO 8601 format." });
1762
+ const base = oc.errors({ BAD_REQUEST: {} });
1763
+ const createEnvironmentContractV1 = base.route({
1275
1764
  path: "/v1/environments",
1276
1765
  method: "POST",
1277
1766
  summary: "Create an environment",
1278
1767
  description: "Create an environment for a project",
1279
1768
  tags: ["environments"],
1280
1769
  successDescription: "The environment has been created successfully"
1281
- }).errors({
1282
- NOT_FOUND: {},
1283
- BAD_REQUEST: {}
1284
- }).input(z.object({
1770
+ }).errors({ NOT_FOUND: {} }).input(z.object({
1285
1771
  projectId: z.string().describe("The ID of the project to create the environment for"),
1286
1772
  name: z.string().min(1).describe("The name of the environment"),
1287
1773
  sourceBranch: z.string().min(1).describe("The branch used to build the environment"),
@@ -1294,7 +1780,7 @@ const createEnvironmentContractV1 = oc.route({
1294
1780
  createdAt: z.coerce.date(),
1295
1781
  projectId: z.string().describe("The ID of the project the environment belongs to")
1296
1782
  }));
1297
- const getEnvironmentContractV1 = oc.route({
1783
+ const getEnvironmentContractV1 = base.route({
1298
1784
  path: "/v1/environments/{environmentId}",
1299
1785
  method: "GET",
1300
1786
  summary: "Get an environment",
@@ -1310,6 +1796,14 @@ const getEnvironmentContractV1 = oc.route({
1310
1796
  createdAt: z.coerce.date(),
1311
1797
  projectId: z.string()
1312
1798
  }));
1799
+ const deleteEnvironmentContractV1 = base.route({
1800
+ path: "/v1/environments/{environmentId}",
1801
+ method: "DELETE",
1802
+ summary: "Delete an environment",
1803
+ description: "All environments can be deleted except the production environment. This operation is not reversible: associated logs, analytics, and metrics are deleted as well.",
1804
+ tags: ["environments"],
1805
+ successDescription: "The environment has been deleted successfully"
1806
+ }).errors({ NOT_FOUND: {} }).input(z.object({ environmentId: z.string().describe("The ID of the environment") })).output(z.object({ success: z.literal(true) }));
1313
1807
  const domainSchema = z.object({
1314
1808
  domain: z.string(),
1315
1809
  status: z.enum([
@@ -1351,7 +1845,7 @@ const projectOutputSchema = z.object({
1351
1845
  productionEnvironment: productionEnvironmentSchema.nullable(),
1352
1846
  environments: z.array(environmentSchema)
1353
1847
  });
1354
- const getProjectContractV1 = oc.route({
1848
+ const getProjectContractV1 = base.route({
1355
1849
  path: "/v1/projects/{projectId}",
1356
1850
  method: "GET",
1357
1851
  summary: "Get a project",
@@ -1359,18 +1853,15 @@ const getProjectContractV1 = oc.route({
1359
1853
  tags: ["projects"],
1360
1854
  successDescription: "The project details"
1361
1855
  }).errors({ NOT_FOUND: {} }).input(z.object({ projectId: z.string().describe("The ID of the project") })).output(projectOutputSchema);
1362
- const listProjectsContractV1 = oc.route({
1856
+ const listProjectsContractV1 = base.route({
1363
1857
  path: "/v1/projects",
1364
1858
  method: "GET",
1365
1859
  summary: "List projects",
1366
1860
  description: "List all projects for a team",
1367
1861
  tags: ["projects"],
1368
1862
  successDescription: "The list of projects"
1369
- }).errors({
1370
- NOT_FOUND: {},
1371
- BAD_REQUEST: {}
1372
- }).input(z.object({ teamId: z.string().optional() }).optional()).output(z.array(projectOutputSchema));
1373
- const createProjectContractV1 = oc.route({
1863
+ }).errors({ NOT_FOUND: {} }).input(z.object({ teamId: z.string().optional() }).optional()).output(z.array(projectOutputSchema));
1864
+ const createProjectContractV1 = base.route({
1374
1865
  path: "/v1/projects",
1375
1866
  method: "POST",
1376
1867
  summary: "Create a project",
@@ -1379,7 +1870,6 @@ const createProjectContractV1 = oc.route({
1379
1870
  successDescription: "The project has been created successfully"
1380
1871
  }).errors({
1381
1872
  NOT_FOUND: {},
1382
- BAD_REQUEST: {},
1383
1873
  FORBIDDEN: {}
1384
1874
  }).input(z.object({
1385
1875
  teamId: z.string().optional(),
@@ -1420,7 +1910,7 @@ const environmentVariableOutputSchema = z.object({
1420
1910
  isSecret: z.boolean(),
1421
1911
  createdAt: z.coerce.date()
1422
1912
  });
1423
- const listEnvironmentVariablesContractV1 = oc.route({
1913
+ const listEnvironmentVariablesContractV1 = base.route({
1424
1914
  path: "/v1/environments/{environmentId}/environment-variables",
1425
1915
  method: "GET",
1426
1916
  summary: "List environment variables",
@@ -1428,48 +1918,39 @@ const listEnvironmentVariablesContractV1 = oc.route({
1428
1918
  tags: ["environments"],
1429
1919
  successDescription: "The list of environment variables"
1430
1920
  }).errors({ NOT_FOUND: {} }).input(z.object({ environmentId: z.string().describe("The ID of the environment") })).output(z.array(environmentVariableOutputSchema));
1431
- const createEnvironmentVariablesContractV1 = oc.route({
1921
+ const createEnvironmentVariablesContractV1 = base.route({
1432
1922
  path: "/v1/environments/{environmentId}/environment-variables",
1433
1923
  method: "POST",
1434
1924
  summary: "Add environment variables",
1435
1925
  description: "Add one or more environment variables to an environment",
1436
1926
  tags: ["environments"],
1437
1927
  successDescription: "The environment variables have been added successfully"
1438
- }).errors({
1439
- NOT_FOUND: {},
1440
- BAD_REQUEST: {}
1441
- }).input(z.object({
1928
+ }).errors({ NOT_FOUND: {} }).input(z.object({
1442
1929
  environmentId: z.string().describe("The ID of the environment"),
1443
1930
  environmentVariables: environmentVariablesSchema
1444
1931
  })).output(z.object({ success: z.literal(true) }));
1445
- const updateEnvironmentVariableContractV1 = oc.route({
1932
+ const updateEnvironmentVariableContractV1 = base.route({
1446
1933
  path: "/v1/environment-variables/{environmentVariableId}",
1447
1934
  method: "PATCH",
1448
1935
  summary: "Update an environment variable",
1449
1936
  description: "Update an environment variable by ID",
1450
1937
  tags: ["environments"],
1451
1938
  successDescription: "The environment variable has been updated successfully"
1452
- }).errors({
1453
- NOT_FOUND: {},
1454
- BAD_REQUEST: {}
1455
- }).input(z.object({
1939
+ }).errors({ NOT_FOUND: {} }).input(z.object({
1456
1940
  environmentVariableId: z.string().describe("The ID of the environment variable"),
1457
1941
  key: environmentVariableSchema.shape.key,
1458
1942
  value: environmentVariableSchema.shape.value.optional(),
1459
1943
  isSecret: environmentVariableSchema.shape.isSecret.optional()
1460
1944
  })).output(z.object({ success: z.literal(true) }));
1461
- const deleteEnvironmentVariableContractV1 = oc.route({
1945
+ const deleteEnvironmentVariableContractV1 = base.route({
1462
1946
  path: "/v1/environment-variables/{environmentVariableId}",
1463
1947
  method: "DELETE",
1464
1948
  summary: "Delete an environment variable",
1465
1949
  description: "Delete an environment variable by ID",
1466
1950
  tags: ["environments"],
1467
1951
  successDescription: "The environment variable has been deleted successfully"
1468
- }).errors({
1469
- NOT_FOUND: {},
1470
- BAD_REQUEST: {}
1471
- }).input(z.object({ environmentVariableId: z.string().describe("The ID of the environment variable") })).output(z.object({ success: z.literal(true) }));
1472
- const deleteProjectContractV1 = oc.route({
1952
+ }).errors({ NOT_FOUND: {} }).input(z.object({ environmentVariableId: z.string().describe("The ID of the environment variable") })).output(z.object({ success: z.literal(true) }));
1953
+ const deleteProjectContractV1 = base.route({
1473
1954
  path: "/v1/projects/{projectId}",
1474
1955
  method: "DELETE",
1475
1956
  summary: "Delete a project",
@@ -1477,7 +1958,7 @@ const deleteProjectContractV1 = oc.route({
1477
1958
  tags: ["projects"],
1478
1959
  successDescription: "The project has been deleted successfully"
1479
1960
  }).errors({ NOT_FOUND: {} }).input(z.object({ projectId: z.string().describe("The ID of the project") })).output(z.object({ success: z.literal(true) }));
1480
- const updateProjectContractV1 = oc.route({
1961
+ const updateProjectContractV1 = base.route({
1481
1962
  path: "/v1/projects/{projectId}",
1482
1963
  method: "PATCH",
1483
1964
  summary: "Update a project",
@@ -1486,14 +1967,13 @@ const updateProjectContractV1 = oc.route({
1486
1967
  successDescription: "The project has been updated successfully"
1487
1968
  }).errors({
1488
1969
  NOT_FOUND: {},
1489
- BAD_REQUEST: {},
1490
1970
  FORBIDDEN: {}
1491
1971
  }).input(z.object({
1492
1972
  projectId: z.string().describe("The ID of the project"),
1493
1973
  name: z.string().min(1).max(100).optional().describe("The new name for the project"),
1494
1974
  sourceRepository: z.string().nullable().optional().describe("The source repository to connect to the project")
1495
1975
  })).output(projectOutputSchema);
1496
- const deployEnvironmentContractV1 = oc.route({
1976
+ const deployEnvironmentContractV1 = base.route({
1497
1977
  path: "/v1/environments/{environmentId}/deploy",
1498
1978
  method: "POST",
1499
1979
  summary: "Deploy an environment",
@@ -1502,27 +1982,25 @@ const deployEnvironmentContractV1 = oc.route({
1502
1982
  successDescription: "The environment has been deployed successfully"
1503
1983
  }).errors({
1504
1984
  NOT_FOUND: {},
1505
- BAD_REQUEST: {}
1985
+ CONFLICT: {}
1506
1986
  }).input(z.object({
1507
1987
  environmentId: z.string().describe("The ID of the environment to deploy"),
1508
- token: z.string().describe("The token to identify the source archive").optional()
1988
+ token: z.string().describe("The token to identify the source archive").optional(),
1989
+ settings: buildSettingsSchema.extend({ transport: transportSchema }).optional().describe("Project settings detected by the client from the source. When provided, the server skips downloading and extracting the source archive to detect them.")
1509
1990
  })).output(deploymentSchema);
1510
- const uploadDeploymentArtifactContractV1 = oc.route({
1991
+ const uploadDeploymentArtifactContractV1 = base.route({
1511
1992
  path: "/v1/deployments/upload",
1512
1993
  method: "POST",
1513
1994
  summary: "Upload deployment artifacts",
1514
1995
  description: "Return a presigned S3 URL to upload a deployment artifact",
1515
1996
  tags: ["deployments"],
1516
1997
  successDescription: "The presigned upload URL has been generated successfully"
1517
- }).errors({
1518
- NOT_FOUND: {},
1519
- BAD_REQUEST: {}
1520
- }).input(z.object({ teamId: z.string().optional() }).optional()).output(z.object({
1998
+ }).errors({ NOT_FOUND: {} }).input(z.object({ teamId: z.string().optional() }).optional()).output(z.object({
1521
1999
  uploadUrl: z.url().describe("Presigned S3 URL to upload the source archive with HTTP PUT"),
1522
2000
  token: z.string().describe("Token to identify the source archive"),
1523
2001
  expiresAt: z.coerce.date().describe("Expiration date of the presigned URL")
1524
2002
  }));
1525
- const listDeploymentsContractV1 = oc.route({
2003
+ const listDeploymentsContractV1 = base.route({
1526
2004
  path: "/v1/projects/{projectId}/deployments",
1527
2005
  method: "GET",
1528
2006
  summary: "List project deployments",
@@ -1534,7 +2012,7 @@ const listDeploymentsContractV1 = oc.route({
1534
2012
  status: z.array(deploymentStatusSchema).optional().describe("Filter by one or more statuses"),
1535
2013
  environmentId: z.string().optional().describe("Filter by environment ID")
1536
2014
  })).output(z.array(deploymentSchema));
1537
- const getDeploymentContractV1 = oc.route({
2015
+ const getDeploymentContractV1 = base.route({
1538
2016
  path: "/v1/deployments/{deploymentId}",
1539
2017
  method: "GET",
1540
2018
  summary: "Get a deployment",
@@ -1542,20 +2020,32 @@ const getDeploymentContractV1 = oc.route({
1542
2020
  tags: ["deployments"],
1543
2021
  successDescription: "The deployment details"
1544
2022
  }).errors({ NOT_FOUND: {} }).input(z.object({ deploymentId: z.string().describe("The ID of the deployment") })).output(deploymentSchema);
1545
- const getLogsContractV1 = oc.route({
2023
+ const logEntrySchema = z.object({
2024
+ timestamp: z.coerce.date(),
2025
+ type: z.enum([
2026
+ "START",
2027
+ "END",
2028
+ "INFO",
2029
+ "ERROR",
2030
+ "WARNING",
2031
+ "DEBUG"
2032
+ ]),
2033
+ requestId: z.string(),
2034
+ content: z.string().optional(),
2035
+ method: z.string().optional(),
2036
+ durationInMs: z.number().optional()
2037
+ });
2038
+ const getLogsContractV1 = base.route({
1546
2039
  path: "/v1/environments/{environmentId}/logs",
1547
2040
  method: "GET",
1548
2041
  summary: "Get logs",
1549
2042
  description: "Get logs for an environment",
1550
2043
  tags: ["environments"],
1551
2044
  successDescription: "The logs"
1552
- }).errors({
1553
- NOT_FOUND: {},
1554
- BAD_REQUEST: {}
1555
- }).input(z.object({
2045
+ }).errors({ NOT_FOUND: {} }).input(z.object({
1556
2046
  environmentId: z.string().describe("The ID of the environment"),
1557
- since: z.string().refine(isValidLogTimeInput, { message: "Invalid time. Use relative (1h, 30m, 2d) or ISO 8601 format." }).optional().describe("Start time — ISO 8601 (2024-01-01T00:00:00Z) or relative (1h, 30m, 2d)"),
1558
- until: z.string().refine(isValidLogTimeInput, { message: "Invalid time. Use relative (1h, 30m, 2d) or ISO 8601 format." }).optional().describe("End time — ISO 8601 or relative"),
2047
+ since: timeInputSchema.optional().describe("Start time — ISO 8601 (2024-01-01T00:00:00Z) or relative (1h, 30m, 2d)"),
2048
+ until: timeInputSchema.optional().describe("End time — ISO 8601 or relative"),
1559
2049
  limit: z.coerce.number().int().min(1).max(1e3).default(1e3).describe("Maximum number of log entries to return."),
1560
2050
  level: z.array(z.enum([
1561
2051
  "INFO",
@@ -1563,37 +2053,20 @@ const getLogsContractV1 = oc.route({
1563
2053
  "WARNING",
1564
2054
  "DEBUG"
1565
2055
  ])).optional().describe("Filter by log level"),
1566
- search: z.string().optional().describe("Filter pattern to search for in log content"),
2056
+ search: logSearchSchema.optional().describe("Term to search for in log content"),
1567
2057
  nextToken: z.string().optional().describe("Pagination token from a previous response")
1568
2058
  })).output(z.object({
1569
- logs: z.array(z.object({
1570
- timestamp: z.coerce.date(),
1571
- type: z.enum([
1572
- "START",
1573
- "END",
1574
- "INFO",
1575
- "ERROR",
1576
- "WARNING",
1577
- "DEBUG"
1578
- ]),
1579
- requestId: z.string(),
1580
- content: z.string().optional(),
1581
- method: z.string().optional(),
1582
- durationInMs: z.number().optional()
1583
- })),
2059
+ logs: z.array(logEntrySchema),
1584
2060
  nextToken: z.string().nullable()
1585
2061
  }));
1586
- const getLatestLogsContractV1 = oc.route({
2062
+ const getLatestLogsContractV1 = base.route({
1587
2063
  path: "/v1/environments/{environmentId}/latest-logs",
1588
2064
  method: "GET",
1589
2065
  summary: "Get latest logs",
1590
2066
  description: "Get the N most recent logs for an environment",
1591
2067
  tags: ["environments"],
1592
2068
  successDescription: "The latest logs"
1593
- }).errors({
1594
- NOT_FOUND: {},
1595
- BAD_REQUEST: {}
1596
- }).input(z.object({
2069
+ }).errors({ NOT_FOUND: {} }).input(z.object({
1597
2070
  environmentId: z.string().describe("The ID of the environment"),
1598
2071
  limit: z.coerce.number().int().min(1).max(1e3).default(100).describe("Number of most recent log entries to return"),
1599
2072
  level: z.array(z.enum([
@@ -1602,23 +2075,9 @@ const getLatestLogsContractV1 = oc.route({
1602
2075
  "WARNING",
1603
2076
  "DEBUG"
1604
2077
  ])).optional().describe("Filter by log level"),
1605
- search: z.string().optional().describe("Filter pattern to search for in log content")
1606
- })).output(z.object({ logs: z.array(z.object({
1607
- timestamp: z.coerce.date(),
1608
- type: z.enum([
1609
- "START",
1610
- "END",
1611
- "INFO",
1612
- "ERROR",
1613
- "WARNING",
1614
- "DEBUG"
1615
- ]),
1616
- requestId: z.string(),
1617
- content: z.string().optional(),
1618
- method: z.string().optional(),
1619
- durationInMs: z.number().optional()
1620
- })) }));
1621
- const getDeploymentLogsContractV1 = oc.route({
2078
+ search: logSearchSchema.optional().describe("Term to search for in log content")
2079
+ })).output(z.object({ logs: z.array(logEntrySchema) }));
2080
+ const getDeploymentLogsContractV1 = base.route({
1622
2081
  path: "/v1/deployments/{deploymentId}/logs",
1623
2082
  method: "GET",
1624
2083
  summary: "Get deployment logs",
@@ -1645,22 +2104,19 @@ const analyticsTimeSeriesSchema = z.object({
1645
2104
  output_token_mean: z.array(analyticsDataPointSchema),
1646
2105
  task_count: z.array(analyticsDataPointSchema)
1647
2106
  });
1648
- const getProjectAnalyticsContractV1 = oc.route({
2107
+ const getProjectAnalyticsContractV1 = base.route({
1649
2108
  path: "/v1/analytics/{projectId}",
1650
2109
  method: "GET",
1651
2110
  summary: "Get project analytics",
1652
2111
  description: "Get analytics data for a project over a time range",
1653
2112
  tags: ["analytics"],
1654
2113
  successDescription: "The project analytics data"
1655
- }).errors({
1656
- NOT_FOUND: {},
1657
- BAD_REQUEST: {}
1658
- }).input(z.object({
2114
+ }).errors({ NOT_FOUND: {} }).input(z.object({
1659
2115
  projectId: z.string().describe("The ID of the project"),
1660
2116
  startTimestamp: z.coerce.number().describe("Start timestamp in milliseconds"),
1661
2117
  endTimestamp: z.coerce.number().describe("End timestamp in milliseconds"),
1662
2118
  timeZone: z.string().describe("IANA timezone (e.g. Europe/Paris)")
1663
- }).refine(({ startTimestamp, endTimestamp }) => endTimestamp - startTimestamp > 0, { message: "End date must be after start date" }).refine(({ startTimestamp, endTimestamp }) => endTimestamp - startTimestamp <= 744 * 60 * 60 * 1e3, { message: "Date range must be less than 1 month" }).refine(({ timeZone }) => Intl.supportedValuesOf("timeZone").includes(timeZone), { message: "Time zone must be a valid IANA timezone" })).output(z.object({
2119
+ }).refine(({ startTimestamp, endTimestamp }) => endTimestamp - startTimestamp > 0, { message: "End date must be after start date" }).refine(({ startTimestamp, endTimestamp }) => endTimestamp - startTimestamp <= 26784e5, { message: "Date range must be less than 1 month" }).refine(({ timeZone }) => isValidIanaTimeZone(timeZone), { message: "Time zone must be a valid IANA timezone" })).output(z.object({
1664
2120
  metadata: z.object({
1665
2121
  startTimestamp: z.number(),
1666
2122
  endTimestamp: z.number(),
@@ -1670,7 +2126,132 @@ const getProjectAnalyticsContractV1 = oc.route({
1670
2126
  }),
1671
2127
  timeSeries: analyticsTimeSeriesSchema
1672
2128
  }));
1673
- const listTeamsContractV1 = oc.route({
2129
+ const paginatedInsightsInputShape = {
2130
+ environmentId: z.string().describe("The ID of the environment"),
2131
+ since: timeInputSchema.default("7d").describe("Start time — ISO 8601 (2024-01-01T00:00:00Z) or relative (1h, 30m, 2d)"),
2132
+ until: timeInputSchema.optional().describe("End time — ISO 8601 or relative"),
2133
+ limit: z.coerce.number().int().min(1).max(200).default(50),
2134
+ offset: z.coerce.number().int().min(0).default(0),
2135
+ search: z.string().trim().min(1).max(200).optional()
2136
+ };
2137
+ const listIntentsContractV1 = base.route({
2138
+ path: "/v1/environments/{environmentId}/intents",
2139
+ method: "GET",
2140
+ summary: "List intents",
2141
+ description: "List grouped user intents for an environment over a time range",
2142
+ tags: ["insights"],
2143
+ successDescription: "The grouped user intents"
2144
+ }).errors({ NOT_FOUND: {} }).input(z.object({
2145
+ ...paginatedInsightsInputShape,
2146
+ tools: z.array(z.string().trim().min(1)).min(1).max(100).optional(),
2147
+ clientIds: z.array(z.string().min(1)).min(1).max(100).optional(),
2148
+ categoryIds: z.array(z.string().trim().min(1)).min(1).max(100).optional(),
2149
+ sortDir: z.enum(["asc", "desc"]).default("desc")
2150
+ })).output(z.object({
2151
+ intents: z.array(z.object({
2152
+ id: z.string(),
2153
+ intentIds: z.array(z.string()).min(1),
2154
+ environmentId: z.string(),
2155
+ message: z.string(),
2156
+ toolName: z.string(),
2157
+ createdAt: z.coerce.date(),
2158
+ occurrenceCount: z.number().int().positive(),
2159
+ clientName: z.string().nullable(),
2160
+ clientId: z.string().nullable(),
2161
+ categories: z.array(z.object({
2162
+ id: z.string(),
2163
+ name: z.string(),
2164
+ color: intentCategoryColorSchema
2165
+ }))
2166
+ })),
2167
+ totalCount: z.number().int().nonnegative()
2168
+ }));
2169
+ const listFeedbacksContractV1 = base.route({
2170
+ path: "/v1/environments/{environmentId}/feedbacks",
2171
+ method: "GET",
2172
+ summary: "List feedbacks",
2173
+ description: "List user feedback for an environment over a time range",
2174
+ tags: ["insights"],
2175
+ successDescription: "The user feedback"
2176
+ }).errors({ NOT_FOUND: {} }).input(z.object({
2177
+ ...paginatedInsightsInputShape,
2178
+ clientIds: z.array(z.string().min(1)).min(1).max(100).optional()
2179
+ })).output(z.object({
2180
+ feedbacks: z.array(feedbackSchema.extend({ clientId: z.string().nullable() })),
2181
+ totalCount: z.number().int().nonnegative()
2182
+ }));
2183
+ const intentCategoryNameSchema = z.string().trim().min(1).max(100).describe("The category name");
2184
+ const categorizableIntentIdsSchema = z.array(z.string().trim().min(1)).min(1).max(100).describe("IDs of the intents to categorize");
2185
+ const listIntentCategoriesContractV1 = base.route({
2186
+ path: "/v1/environments/{environmentId}/intent-categories",
2187
+ method: "GET",
2188
+ summary: "List intent categories",
2189
+ description: "List intent categories for an environment, including how many intents each category is linked to",
2190
+ tags: ["insights"],
2191
+ successDescription: "The intent categories"
2192
+ }).errors({ NOT_FOUND: {} }).input(z.object({ environmentId: z.string().describe("The ID of the environment") })).output(z.array(intentCategorySummarySchema));
2193
+ const createIntentCategoryContractV1 = base.route({
2194
+ path: "/v1/environments/{environmentId}/intent-categories",
2195
+ method: "POST",
2196
+ summary: "Create an intent category",
2197
+ description: "Create an intent category, optionally linking it to existing intents",
2198
+ tags: ["insights"],
2199
+ successDescription: "The created intent category"
2200
+ }).errors({ NOT_FOUND: {} }).input(z.object({
2201
+ environmentId: z.string().describe("The ID of the environment"),
2202
+ name: intentCategoryNameSchema,
2203
+ color: intentCategoryColorSchema.optional().describe("The category color; derived from the name when omitted"),
2204
+ intentIds: categorizableIntentIdsSchema.optional().describe("IDs of intents to link to the new category")
2205
+ })).output(intentCategorySchema);
2206
+ const updateIntentCategoryContractV1 = base.route({
2207
+ path: "/v1/environments/{environmentId}/intent-categories/{categoryId}",
2208
+ method: "PATCH",
2209
+ summary: "Update an intent category",
2210
+ description: "Rename or recolor an intent category",
2211
+ tags: ["insights"],
2212
+ successDescription: "The updated intent category"
2213
+ }).errors({ NOT_FOUND: {} }).input(z.object({
2214
+ environmentId: z.string().describe("The ID of the environment"),
2215
+ categoryId: z.string().describe("The ID of the category"),
2216
+ name: intentCategoryNameSchema.optional(),
2217
+ color: intentCategoryColorSchema.optional().describe("The category color")
2218
+ }).refine(({ name, color }) => name !== void 0 || color !== void 0, { message: "At least one of name or color must be provided" })).output(intentCategorySchema);
2219
+ const deleteIntentCategoryContractV1 = base.route({
2220
+ path: "/v1/environments/{environmentId}/intent-categories/{categoryId}",
2221
+ method: "DELETE",
2222
+ summary: "Delete an intent category",
2223
+ description: "Delete an intent category; its intents are unlinked but not deleted",
2224
+ tags: ["insights"],
2225
+ successDescription: "The intent category has been deleted successfully"
2226
+ }).errors({ NOT_FOUND: {} }).input(z.object({
2227
+ environmentId: z.string().describe("The ID of the environment"),
2228
+ categoryId: z.string().describe("The ID of the category")
2229
+ })).output(z.object({ success: z.literal(true) }));
2230
+ const linkIntentCategoryContractV1 = base.route({
2231
+ path: "/v1/environments/{environmentId}/intent-categories/{categoryId}/link",
2232
+ method: "POST",
2233
+ summary: "Link an intent category",
2234
+ description: "Link an intent category to intents; already linked intents are ignored",
2235
+ tags: ["insights"],
2236
+ successDescription: "The intents have been linked successfully"
2237
+ }).errors({ NOT_FOUND: {} }).input(z.object({
2238
+ environmentId: z.string().describe("The ID of the environment"),
2239
+ categoryId: z.string().describe("The ID of the category"),
2240
+ intentIds: categorizableIntentIdsSchema
2241
+ })).output(z.object({ success: z.literal(true) }));
2242
+ const unlinkIntentCategoryContractV1 = base.route({
2243
+ path: "/v1/environments/{environmentId}/intent-categories/{categoryId}/unlink",
2244
+ method: "POST",
2245
+ summary: "Unlink an intent category",
2246
+ description: "Unlink an intent category from intents; intents without the category are ignored",
2247
+ tags: ["insights"],
2248
+ successDescription: "The intents have been unlinked successfully"
2249
+ }).errors({ NOT_FOUND: {} }).input(z.object({
2250
+ environmentId: z.string().describe("The ID of the environment"),
2251
+ categoryId: z.string().describe("The ID of the category"),
2252
+ intentIds: categorizableIntentIdsSchema
2253
+ })).output(z.object({ success: z.literal(true) }));
2254
+ const listTeamsContractV1 = base.route({
1674
2255
  path: "/v1/teams",
1675
2256
  method: "GET",
1676
2257
  summary: "List teams",
@@ -1683,7 +2264,22 @@ const listTeamsContractV1 = oc.route({
1683
2264
  createdAt: z.coerce.date(),
1684
2265
  hasStripeAccount: z.boolean()
1685
2266
  })));
1686
- const getTunnelTicketContractV1 = oc.route({
2267
+ const getTeamUsageContractV1 = base.route({
2268
+ path: "/v1/teams/{teamId}/usage",
2269
+ method: "GET",
2270
+ summary: "Get team usage",
2271
+ description: "Get the MCP request usage of a team for its current billing window. A team that has made no request in the window reports zero.",
2272
+ tags: ["teams"],
2273
+ successDescription: "The current billing window usage"
2274
+ }).errors({ NOT_FOUND: {} }).input(z.object({ teamId: z.string().describe("The ID of the team") })).output(z.object({
2275
+ teamId: z.string(),
2276
+ plan: subscriptionPlanSchema.nullable().describe("The plan in force for the window, null on the Free plan"),
2277
+ periodStart: z.coerce.date().describe("Start of the current billing window"),
2278
+ periodEnd: z.coerce.date().describe("End of the current billing window"),
2279
+ requestCount: z.number().int().describe("MCP requests settled during the current billing window"),
2280
+ includedRequests: z.number().int().nullable().describe("Requests included in the plan for one window, null when the allowance is contract-specific")
2281
+ }));
2282
+ const getTunnelTicketContractV1 = base.route({
1687
2283
  path: "/v1/tunnels/ticket",
1688
2284
  method: "GET",
1689
2285
  summary: "Get a tunnel ticket",
@@ -1695,16 +2291,13 @@ const getTunnelTicketContractV1 = oc.route({
1695
2291
  ticket: z.string().describe("The signed tunnel ticket"),
1696
2292
  tunnelHost: z.string().describe("The tunnel host to connect to")
1697
2293
  }));
1698
- const publishServerContractV1 = oc.route({
2294
+ const publishServerContractV1 = base.route({
1699
2295
  path: "/v1/distribution/publish",
1700
2296
  method: "POST",
1701
2297
  summary: "Publish a server to the MCP registry",
1702
2298
  tags: ["distribution"],
1703
2299
  successDescription: "The server has been published successfully"
1704
- }).errors({
1705
- NOT_FOUND: {},
1706
- BAD_REQUEST: {}
1707
- }).input(z.object({
2300
+ }).errors({ NOT_FOUND: {} }).input(z.object({
1708
2301
  projectId: z.string(),
1709
2302
  domain: z.string(),
1710
2303
  title: z.string().min(1).max(100),
@@ -1713,17 +2306,14 @@ const publishServerContractV1 = oc.route({
1713
2306
  iconSrc: z.url().max(255).optional(),
1714
2307
  dryRun: z.boolean().optional()
1715
2308
  })).output(z.object({ serverFields: serverFieldsSchema }));
1716
- const getServerInfoContractV1 = oc.route({
2309
+ const getServerInfoContractV1 = base.route({
1717
2310
  path: "/v1/distribution/get",
1718
2311
  method: "GET",
1719
2312
  summary: "Get server info",
1720
2313
  description: "Get info about a server",
1721
2314
  tags: ["distribution"],
1722
2315
  successDescription: "The server info"
1723
- }).errors({
1724
- NOT_FOUND: {},
1725
- BAD_REQUEST: {}
1726
- }).input(z.object({
2316
+ }).errors({ NOT_FOUND: {} }).input(z.object({
1727
2317
  projectId: z.string(),
1728
2318
  domain: z.string()
1729
2319
  })).output(z.object({ serverFields: serverFieldsSchema }));
@@ -1742,7 +2332,7 @@ const playgroundOutputSchema = z.object({
1742
2332
  isPlaygroundEnabled: z.boolean(),
1743
2333
  serverMetadata: playgroundServerMetadataOutputSchema.nullable()
1744
2334
  });
1745
- const getPlaygroundContractV1 = oc.route({
2335
+ const getPlaygroundContractV1 = base.route({
1746
2336
  path: "/v1/environments/{environmentId}/playground",
1747
2337
  method: "GET",
1748
2338
  summary: "Get playground configuration",
@@ -1750,17 +2340,14 @@ const getPlaygroundContractV1 = oc.route({
1750
2340
  tags: ["environments"],
1751
2341
  successDescription: "The playground configuration"
1752
2342
  }).errors({ NOT_FOUND: {} }).input(z.object({ environmentId: z.string().describe("The ID of the environment") })).output(playgroundOutputSchema);
1753
- const upsertPlaygroundContractV1 = oc.route({
2343
+ const upsertPlaygroundContractV1 = base.route({
1754
2344
  path: "/v1/environments/{environmentId}/playground",
1755
2345
  method: "PUT",
1756
2346
  summary: "Update playground configuration",
1757
2347
  description: "Update the playground configuration for an environment. All fields are optional — only provided fields are updated.",
1758
2348
  tags: ["environments"],
1759
2349
  successDescription: "The updated playground configuration"
1760
- }).errors({
1761
- NOT_FOUND: {},
1762
- BAD_REQUEST: {}
1763
- }).input(z.object({
2350
+ }).errors({ NOT_FOUND: {} }).input(z.object({
1764
2351
  environmentId: z.string().describe("The ID of the environment"),
1765
2352
  isPlaygroundEnabled: z.boolean().optional(),
1766
2353
  name: z.string().min(1).max(100).optional(),
@@ -1768,7 +2355,7 @@ const upsertPlaygroundContractV1 = oc.route({
1768
2355
  headers: z.array(playgroundHeaderSchema).optional(),
1769
2356
  examplePrompts: z.array(playgroundExamplePromptSchema).max(5).optional()
1770
2357
  })).output(playgroundOutputSchema);
1771
- const createBeaconContractV1 = oc.route({
2358
+ const createBeaconContractV1 = base.route({
1772
2359
  path: "/v1/beacon/audits",
1773
2360
  method: "POST",
1774
2361
  summary: "Create a beacon audit",
@@ -1777,7 +2364,6 @@ const createBeaconContractV1 = oc.route({
1777
2364
  successDescription: "The audit has been created"
1778
2365
  }).errors({
1779
2366
  NOT_FOUND: {},
1780
- BAD_REQUEST: {},
1781
2367
  DNS_RESOLUTION_FAILED: { status: 400 }
1782
2368
  }).input(z.object({
1783
2369
  targetUrl: z.url().describe("The HTTPS URL of the MCP server to audit"),
@@ -1785,7 +2371,7 @@ const createBeaconContractV1 = oc.route({
1785
2371
  projectId: z.string().optional().describe("The project ID to associate the audit with"),
1786
2372
  excludeCategories: z.array(checkCategorySchema).optional().describe("Check categories to exclude from the audit")
1787
2373
  })).output(z.object({ id: z.string() }));
1788
- const getBeaconContractV1 = oc.route({
2374
+ const getBeaconContractV1 = base.route({
1789
2375
  path: "/v1/beacon/audits/{auditId}",
1790
2376
  method: "GET",
1791
2377
  summary: "Get a beacon audit",
@@ -1800,9 +2386,73 @@ const getBeaconContractV1 = oc.route({
1800
2386
  createdAt: z.coerce.date(),
1801
2387
  report: auditReportWithScreenshotsSchema.nullable()
1802
2388
  }));
2389
+ const PLATFORM_DESCRIPTION = "The directory the package targets: `chatgpt` for the OpenAI App Directory, `claudeai` for the Anthropic MCP Directory";
2390
+ const submissionIdSchema = z.string().describe("The ID of the submission package");
2391
+ const claudeSubmissionUpdateSchema = claudeSubmissionDraftSchema.strict();
2392
+ const chatgptSubmissionUpdateSchema = chatgptSubmissionDraftSchema.strict();
2393
+ const createSubmissionContractV1 = base.route({
2394
+ path: "/v1/submissions",
2395
+ method: "POST",
2396
+ summary: "Create a submission package",
2397
+ description: "Create a submission package for an environment. Alpic reads the environment's live MCP server and prefills every field it can infer, so the response already carries the populated package. The environment must have a successful deployment and must not require authentication.",
2398
+ tags: ["submissions"],
2399
+ successDescription: "The created submission package, with its prefilled fields"
2400
+ }).errors({ NOT_FOUND: {} }).input(z.object({
2401
+ environmentId: z.string().describe("The ID of the environment to build the package from"),
2402
+ platform: platformSchema.describe(PLATFORM_DESCRIPTION)
2403
+ })).output(submissionSchema);
2404
+ const listSubmissionsContractV1 = base.route({
2405
+ path: "/v1/projects/{projectId}/submissions",
2406
+ method: "GET",
2407
+ summary: "List submission packages",
2408
+ description: "List the submission packages of a project, grouped by directory and most recently updated first, optionally narrowed to one environment or one directory",
2409
+ tags: ["submissions"],
2410
+ successDescription: "The list of submission packages"
2411
+ }).errors({ NOT_FOUND: {} }).input(z.object({
2412
+ projectId: z.string().describe("The ID of the project"),
2413
+ environmentId: z.string().optional().describe("Filter by environment ID"),
2414
+ platform: platformSchema.optional().describe(PLATFORM_DESCRIPTION)
2415
+ })).output(z.array(submissionSchema));
2416
+ const getSubmissionContractV1 = base.route({
2417
+ path: "/v1/submissions/{submissionId}",
2418
+ method: "GET",
2419
+ summary: "Get a submission package",
2420
+ description: "Get a submission package by ID, including its form data and the prefill it started from",
2421
+ tags: ["submissions"],
2422
+ successDescription: "The submission package"
2423
+ }).errors({ NOT_FOUND: {} }).input(z.object({ submissionId: submissionIdSchema })).output(submissionSchema);
2424
+ const updateSubmissionContractV1 = base.route({
2425
+ path: "/v1/submissions/{submissionId}",
2426
+ method: "PUT",
2427
+ summary: "Update a submission package",
2428
+ description: "Update the form data of a submission package. Only the fields you send are changed; the rest are left as they are. Unknown field names are rejected rather than ignored, so a typo fails the call. `platform` must match the package's own platform.",
2429
+ tags: ["submissions"],
2430
+ successDescription: "The updated submission package"
2431
+ }).errors({ NOT_FOUND: {} }).input(z.discriminatedUnion("platform", [z.object({
2432
+ submissionId: submissionIdSchema,
2433
+ platform: z.literal("claudeai").describe(PLATFORM_DESCRIPTION),
2434
+ formData: claudeSubmissionUpdateSchema
2435
+ }), z.object({
2436
+ submissionId: submissionIdSchema,
2437
+ platform: z.literal("chatgpt").describe(PLATFORM_DESCRIPTION),
2438
+ formData: chatgptSubmissionUpdateSchema
2439
+ })])).output(submissionSchema);
1803
2440
  const contract = {
1804
- teams: { list: { v1: listTeamsContractV1 } },
2441
+ teams: {
2442
+ list: { v1: listTeamsContractV1 },
2443
+ getUsage: { v1: getTeamUsageContractV1 }
2444
+ },
1805
2445
  analytics: { get: { v1: getProjectAnalyticsContractV1 } },
2446
+ intents: { list: { v1: listIntentsContractV1 } },
2447
+ intentCategories: {
2448
+ list: { v1: listIntentCategoriesContractV1 },
2449
+ create: { v1: createIntentCategoryContractV1 },
2450
+ update: { v1: updateIntentCategoryContractV1 },
2451
+ delete: { v1: deleteIntentCategoryContractV1 },
2452
+ link: { v1: linkIntentCategoryContractV1 },
2453
+ unlink: { v1: unlinkIntentCategoryContractV1 }
2454
+ },
2455
+ feedbacks: { list: { v1: listFeedbacksContractV1 } },
1806
2456
  deployments: {
1807
2457
  list: { v1: listDeploymentsContractV1 },
1808
2458
  get: { v1: getDeploymentContractV1 },
@@ -1812,6 +2462,7 @@ const contract = {
1812
2462
  environments: {
1813
2463
  create: { v1: createEnvironmentContractV1 },
1814
2464
  get: { v1: getEnvironmentContractV1 },
2465
+ delete: { v1: deleteEnvironmentContractV1 },
1815
2466
  deploy: { v1: deployEnvironmentContractV1 },
1816
2467
  getLogs: { v1: getLogsContractV1 },
1817
2468
  getLatestLogs: { v1: getLatestLogsContractV1 }
@@ -1841,7 +2492,39 @@ const contract = {
1841
2492
  beacon: {
1842
2493
  create: { v1: createBeaconContractV1 },
1843
2494
  get: { v1: getBeaconContractV1 }
2495
+ },
2496
+ submissions: {
2497
+ create: { v1: createSubmissionContractV1 },
2498
+ list: { v1: listSubmissionsContractV1 },
2499
+ get: { v1: getSubmissionContractV1 },
2500
+ update: { v1: updateSubmissionContractV1 }
2501
+ }
2502
+ };
2503
+ const { uploadArtifact: _discard, ...deploymentsForDocs } = contract.deployments;
2504
+ const contractForDocs = {
2505
+ ...contract,
2506
+ deployments: deploymentsForDocs
2507
+ };
2508
+ /** Shared by the served `openapi.json` and the snapshot test that guards it, so the two cannot drift. */
2509
+ const OPENAPI_DOC_OPTIONS = {
2510
+ info: {
2511
+ title: "Alpic API",
2512
+ version: "1.0.0"
2513
+ },
2514
+ servers: [{ url: "https://api.alpic.ai" }],
2515
+ security: [{ bearerAuth: [] }],
2516
+ components: { securitySchemes: { bearerAuth: {
2517
+ type: "http",
2518
+ description: "Bearer token for authentication. Use an API key from the API Keys page in team settings, or an OAuth access token.",
2519
+ scheme: "bearer"
2520
+ } } },
2521
+ commonSchemas: {
2522
+ Submission: { schema: submissionSchema },
2523
+ ClaudeSubmissionFormData: { schema: claudeSubmissionDraftSchema },
2524
+ ChatgptSubmissionFormData: { schema: chatgptSubmissionDraftSchema },
2525
+ ClaudeSubmissionFormDataUpdate: { schema: claudeSubmissionUpdateSchema },
2526
+ ChatgptSubmissionFormDataUpdate: { schema: chatgptSubmissionUpdateSchema }
1844
2527
  }
1845
2528
  };
1846
2529
  //#endregion
1847
- export { AUTH_SCOPE_ANY, AUTH_SCOPE_USER, PLATFORM_LABELS, buildSettingsSchema, contract, createEnvironmentContractV1, deploymentStatusSchema, environmentVariableSchema, environmentVariablesSchema, playgroundExamplePromptSchema, playgroundHeaderSchema, runtimeSchema, serverFieldsSchema, transportSchema, updateEnvironmentVariableSchema };
2530
+ export { AI_PLATFORMS, AUTH_SCOPE_ANY, AUTH_SCOPE_USER, INTENT_CATEGORY_COLORS, OPENAPI_DOC_OPTIONS, PLATFORM_LABELS, buildSettingsSchema, chatgptSubmissionUpdateSchema, claudeSubmissionUpdateSchema, contract, contractForDocs, createEnvironmentContractV1, deploymentStatusSchema, environmentVariableSchema, environmentVariablesSchema, intentCategoryColorSchema, playgroundExamplePromptSchema, playgroundHeaderSchema, runtimeSchema, serverFieldsSchema, transportSchema, updateEnvironmentVariableSchema };