diff --git a/.changeset/artifact-apis.md b/.changeset/artifact-apis.md new file mode 100644 index 0000000000..2f554c6a8b --- /dev/null +++ b/.changeset/artifact-apis.md @@ -0,0 +1,5 @@ +--- +"@truefoundry/trueforge": patch +--- + +Add `GET /api/v1/artifacts` to list the caller's artifacts, filterable by session, title substring, and `updated_at` range. diff --git a/.github/fern/openapi/openapi.json b/.github/fern/openapi/openapi.json index d325015bad..c3fd5cf7c4 100644 --- a/.github/fern/openapi/openapi.json +++ b/.github/fern/openapi/openapi.json @@ -331,6 +331,45 @@ ], "type": "object" }, + "Artifact": { + "additionalProperties": false, + "properties": { + "created_at": { + "format": "date-time", + "type": "string" + }, + "created_by_session_id": { + "type": "string" + }, + "created_by_subject": { + "$ref": "#/components/schemas/Subject" + }, + "latest_version": { + "description": "Latest version.", + "type": "integer" + }, + "slug": { + "type": "string" + }, + "title": { + "type": "string" + }, + "updated_at": { + "format": "date-time", + "type": "string" + } + }, + "required": [ + "slug", + "title", + "latest_version", + "created_by_subject", + "created_by_session_id", + "created_at", + "updated_at" + ], + "type": "object" + }, "AskUserQuestionsConfig": { "default": { "enabled": true @@ -2145,6 +2184,24 @@ ], "type": "object" }, + "ListArtifactsResponse": { + "properties": { + "data": { + "items": { + "$ref": "#/components/schemas/Artifact" + }, + "type": "array" + }, + "pagination": { + "$ref": "#/components/schemas/TokenPagination" + } + }, + "required": [ + "data", + "pagination" + ], + "type": "object" + }, "ListAvailableMCPServersResponse": { "properties": { "data": { @@ -7988,6 +8045,103 @@ "x-fern-sdk-method-name": "get_code_snippets" } }, + "/api/v1/artifacts": { + "get": { + "description": "List artifacts created by the caller, most recently updated first. Optionally filter by session, title substring, or `updated_at` range.", + "parameters": [ + { + "description": "Page size. Defaults to 25", + "in": "query", + "name": "limit", + "required": false, + "schema": { + "default": 25, + "description": "Page size. Defaults to 25", + "maximum": 25, + "minimum": 1, + "type": "integer" + } + }, + { + "description": "Opaque token from a previous response `next_page_token`.", + "in": "query", + "name": "page_token", + "required": false, + "schema": { + "description": "Opaque token from a previous response `next_page_token`.", + "type": "string" + } + }, + { + "description": "When set, only artifacts created in this session are returned.", + "in": "query", + "name": "created_by_session_id", + "required": false, + "schema": { + "description": "When set, only artifacts created in this session are returned.", + "minLength": 1, + "type": "string" + } + }, + { + "description": "Case-insensitive substring match on artifact title.", + "in": "query", + "name": "title", + "required": false, + "schema": { + "description": "Case-insensitive substring match on artifact title.", + "minLength": 1, + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ListArtifactsResponse" + } + } + }, + "description": "Paginated artifacts." + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RequestErrorResponse" + } + } + }, + "description": "Invalid query parameters or page token." + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RequestErrorResponse" + } + } + }, + "description": "Unauthenticated." + } + }, + "summary": "List artifacts", + "tags": [ + "Artifacts" + ], + "x-fern-pagination": { + "cursor": "$request.page_token", + "next_cursor": "$response.pagination.next_page_token", + "results": "$response.data" + }, + "x-fern-sdk-group-name": [ + "artifacts" + ], + "x-fern-sdk-method-name": "list" + } + }, "/api/v1/auth/callback": { "get": { "description": "Browser-redirect target hit by the identity provider after login, never called directly by SDK consumers. In local/single-binary mode, redirects straight back into the app.", @@ -12967,6 +13121,9 @@ }, { "name": "Agent Sessions" + }, + { + "name": "Artifacts" } ], "webhooks": {} diff --git a/docs/openapi.json b/docs/openapi.json index d325015bad..c3fd5cf7c4 100644 --- a/docs/openapi.json +++ b/docs/openapi.json @@ -331,6 +331,45 @@ ], "type": "object" }, + "Artifact": { + "additionalProperties": false, + "properties": { + "created_at": { + "format": "date-time", + "type": "string" + }, + "created_by_session_id": { + "type": "string" + }, + "created_by_subject": { + "$ref": "#/components/schemas/Subject" + }, + "latest_version": { + "description": "Latest version.", + "type": "integer" + }, + "slug": { + "type": "string" + }, + "title": { + "type": "string" + }, + "updated_at": { + "format": "date-time", + "type": "string" + } + }, + "required": [ + "slug", + "title", + "latest_version", + "created_by_subject", + "created_by_session_id", + "created_at", + "updated_at" + ], + "type": "object" + }, "AskUserQuestionsConfig": { "default": { "enabled": true @@ -2145,6 +2184,24 @@ ], "type": "object" }, + "ListArtifactsResponse": { + "properties": { + "data": { + "items": { + "$ref": "#/components/schemas/Artifact" + }, + "type": "array" + }, + "pagination": { + "$ref": "#/components/schemas/TokenPagination" + } + }, + "required": [ + "data", + "pagination" + ], + "type": "object" + }, "ListAvailableMCPServersResponse": { "properties": { "data": { @@ -7988,6 +8045,103 @@ "x-fern-sdk-method-name": "get_code_snippets" } }, + "/api/v1/artifacts": { + "get": { + "description": "List artifacts created by the caller, most recently updated first. Optionally filter by session, title substring, or `updated_at` range.", + "parameters": [ + { + "description": "Page size. Defaults to 25", + "in": "query", + "name": "limit", + "required": false, + "schema": { + "default": 25, + "description": "Page size. Defaults to 25", + "maximum": 25, + "minimum": 1, + "type": "integer" + } + }, + { + "description": "Opaque token from a previous response `next_page_token`.", + "in": "query", + "name": "page_token", + "required": false, + "schema": { + "description": "Opaque token from a previous response `next_page_token`.", + "type": "string" + } + }, + { + "description": "When set, only artifacts created in this session are returned.", + "in": "query", + "name": "created_by_session_id", + "required": false, + "schema": { + "description": "When set, only artifacts created in this session are returned.", + "minLength": 1, + "type": "string" + } + }, + { + "description": "Case-insensitive substring match on artifact title.", + "in": "query", + "name": "title", + "required": false, + "schema": { + "description": "Case-insensitive substring match on artifact title.", + "minLength": 1, + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ListArtifactsResponse" + } + } + }, + "description": "Paginated artifacts." + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RequestErrorResponse" + } + } + }, + "description": "Invalid query parameters or page token." + }, + "401": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RequestErrorResponse" + } + } + }, + "description": "Unauthenticated." + } + }, + "summary": "List artifacts", + "tags": [ + "Artifacts" + ], + "x-fern-pagination": { + "cursor": "$request.page_token", + "next_cursor": "$response.pagination.next_page_token", + "results": "$response.data" + }, + "x-fern-sdk-group-name": [ + "artifacts" + ], + "x-fern-sdk-method-name": "list" + } + }, "/api/v1/auth/callback": { "get": { "description": "Browser-redirect target hit by the identity provider after login, never called directly by SDK consumers. In local/single-binary mode, redirects straight back into the app.", @@ -12967,6 +13121,9 @@ }, { "name": "Agent Sessions" + }, + { + "name": "Artifacts" } ], "webhooks": {} diff --git a/packages/trueforge-sdk/package.json b/packages/trueforge-sdk/package.json index 9c1d86994e..187e481838 100644 --- a/packages/trueforge-sdk/package.json +++ b/packages/trueforge-sdk/package.json @@ -55,6 +55,17 @@ }, "default": "./dist/esm/api/resources/agents/exports.mjs" }, + "./artifacts": { + "import": { + "types": "./dist/esm/api/resources/artifacts/exports.d.mts", + "default": "./dist/esm/api/resources/artifacts/exports.mjs" + }, + "require": { + "types": "./dist/cjs/api/resources/artifacts/exports.d.ts", + "default": "./dist/cjs/api/resources/artifacts/exports.js" + }, + "default": "./dist/esm/api/resources/artifacts/exports.mjs" + }, "./auth": { "import": { "types": "./dist/esm/api/resources/auth/exports.d.mts", diff --git a/packages/trueforge-sdk/reference.md b/packages/trueforge-sdk/reference.md index 35b06f4f1e..4e4a1a2b24 100644 --- a/packages/trueforge-sdk/reference.md +++ b/packages/trueforge-sdk/reference.md @@ -412,6 +412,82 @@ await client.agents.delete("agent_id"); + + + + +## Artifacts +
client.artifacts.list({ ...params }) -> core.Page<TrueForge.Artifact, TrueForge.ListArtifactsResponse> +
+
+ +#### 📝 Description + +
+
+ +
+
+ +List artifacts created by the caller, most recently updated first. Optionally filter by session, title substring, or `updated_at` range. +
+
+
+
+ +#### 🔌 Usage + +
+
+ +
+
+ +```typescript +const pageableResponse = await client.artifacts.list(); +for await (const item of pageableResponse) { + console.log(item); +} + +// Or you can manually iterate page-by-page +let page = await client.artifacts.list(); +while (page.hasNextPage()) { + page = await page.getNextPage(); +} + +// You can also access the underlying response +const response = page.response; + +``` +
+
+
+
+ +#### ⚙️ Parameters + +
+
+ +
+
+ +**request:** `TrueForge.ListArtifactsRequest` + +
+
+ +
+
+ +**requestOptions:** `ArtifactsClient.RequestOptions` + +
+
+
+
+ +
diff --git a/packages/trueforge-sdk/src/Client.ts b/packages/trueforge-sdk/src/Client.ts index 839dab1841..c3a05edef4 100644 --- a/packages/trueforge-sdk/src/Client.ts +++ b/packages/trueforge-sdk/src/Client.ts @@ -1,6 +1,7 @@ // This file was auto-generated by Fern from our API Definition. import { AgentsClient } from "./api/resources/agents/client/Client.js"; +import { ArtifactsClient } from "./api/resources/artifacts/client/Client.js"; import { AuthClient } from "./api/resources/auth/client/Client.js"; import { CatalogsClient } from "./api/resources/catalogs/client/Client.js"; import { InternalClient } from "./api/resources/internal/client/Client.js"; @@ -27,6 +28,7 @@ export class TrueForge { protected readonly _options: NormalizedClientOptionsWithAuth; protected _internal: InternalClient | undefined; protected _agents: AgentsClient | undefined; + protected _artifacts: ArtifactsClient | undefined; protected _auth: AuthClient | undefined; protected _server: ServerClient | undefined; protected _mcpServers: McpServersClient | undefined; @@ -51,6 +53,10 @@ export class TrueForge { return (this._agents ??= new AgentsClient(this._options)); } + public get artifacts(): ArtifactsClient { + return (this._artifacts ??= new ArtifactsClient(this._options)); + } + public get auth(): AuthClient { return (this._auth ??= new AuthClient(this._options)); } diff --git a/packages/trueforge-sdk/src/api/resources/artifacts/client/Client.ts b/packages/trueforge-sdk/src/api/resources/artifacts/client/Client.ts new file mode 100644 index 0000000000..9ef598894e --- /dev/null +++ b/packages/trueforge-sdk/src/api/resources/artifacts/client/Client.ts @@ -0,0 +1,139 @@ +// This file was auto-generated by Fern from our API Definition. + +import type { BaseClientOptions, BaseRequestOptions } from "../../../../BaseClient.js"; +import { type NormalizedClientOptionsWithAuth, normalizeClientOptionsWithAuth } from "../../../../BaseClient.js"; +import { mergeHeaders } from "../../../../core/headers.js"; +import * as core from "../../../../core/index.js"; +import { handleNonStatusCodeError } from "../../../../errors/handleNonStatusCodeError.js"; +import * as errors from "../../../../errors/index.js"; +import * as serializers from "../../../../serialization/index.js"; +import * as TrueForge from "../../../index.js"; + +export declare namespace ArtifactsClient { + export type Options = BaseClientOptions; + + export interface RequestOptions extends BaseRequestOptions {} +} + +export class ArtifactsClient { + protected readonly _options: NormalizedClientOptionsWithAuth; + + constructor(options: ArtifactsClient.Options) { + this._options = normalizeClientOptionsWithAuth(options); + } + + /** + * List artifacts created by the caller, most recently updated first. Optionally filter by session, title substring, or `updated_at` range. + * + * @param {TrueForge.ListArtifactsRequest} request + * @param {ArtifactsClient.RequestOptions} requestOptions - Request-specific configuration. + * + * @throws {@link TrueForge.BadRequestError} + * @throws {@link TrueForge.UnauthorizedError} + * @throws {@link errors.TrueForgeError} + * @throws {@link errors.TrueForgeTimeoutError} + * + * @example + * await client.artifacts.list() + */ + public async list( + request: TrueForge.ListArtifactsRequest = {}, + requestOptions?: ArtifactsClient.RequestOptions, + ): Promise> { + const list = core.HttpResponsePromise.interceptFunction( + async ( + request: TrueForge.ListArtifactsRequest, + ): Promise> => { + const { limit = 25, pageToken, createdBySessionId, title } = request; + const _queryParams: Record = { + limit, + page_token: pageToken, + created_by_session_id: createdBySessionId, + title, + }; + const _authRequest: core.AuthRequest = await this._options.authProvider.getAuthRequest(); + const _headers: core.Fetcher.Args["headers"] = mergeHeaders( + _authRequest.headers, + this._options?.headers, + requestOptions?.headers, + ); + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)), + "api/v1/artifacts", + ), + method: "GET", + headers: _headers, + queryString: core.url + .queryBuilder() + .addMany(_queryParams) + .mergeAdditional(requestOptions?.queryParams) + .build(), + timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1000, + maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries, + abortSignal: requestOptions?.abortSignal, + fetchFn: this._options?.fetch, + logging: this._options.logging, + }); + if (_response.ok) { + return { + data: serializers.ListArtifactsResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; + } + if (_response.error.reason === "status-code") { + switch (_response.error.statusCode) { + case 400: + throw new TrueForge.BadRequestError( + serializers.RequestErrorResponse.parseOrThrow(_response.error.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + _response.rawResponse, + ); + case 401: + throw new TrueForge.UnauthorizedError( + serializers.RequestErrorResponse.parseOrThrow(_response.error.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + _response.rawResponse, + ); + default: + throw new errors.TrueForgeError({ + statusCode: _response.error.statusCode, + body: _response.error.body, + rawResponse: _response.rawResponse, + }); + } + } + return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/api/v1/artifacts"); + }, + ); + const dataWithRawResponse = await list(request).withRawResponse(); + return new core.Page({ + response: dataWithRawResponse.data, + rawResponse: dataWithRawResponse.rawResponse, + hasNextPage: (response) => + response?.pagination.nextPageToken != null && + !(typeof response?.pagination.nextPageToken === "string" && response?.pagination.nextPageToken === ""), + getItems: (response) => response?.data ?? [], + loadPage: (response) => { + return list(core.setObjectProperty(request, "pageToken", response?.pagination.nextPageToken)); + }, + }); + } +} diff --git a/packages/trueforge-sdk/src/api/resources/artifacts/client/index.ts b/packages/trueforge-sdk/src/api/resources/artifacts/client/index.ts new file mode 100644 index 0000000000..195f9aa8a8 --- /dev/null +++ b/packages/trueforge-sdk/src/api/resources/artifacts/client/index.ts @@ -0,0 +1 @@ +export * from "./requests/index.js"; diff --git a/packages/trueforge-sdk/src/api/resources/artifacts/client/requests/ListArtifactsRequest.ts b/packages/trueforge-sdk/src/api/resources/artifacts/client/requests/ListArtifactsRequest.ts new file mode 100644 index 0000000000..061303826d --- /dev/null +++ b/packages/trueforge-sdk/src/api/resources/artifacts/client/requests/ListArtifactsRequest.ts @@ -0,0 +1,16 @@ +// This file was auto-generated by Fern from our API Definition. + +/** + * @example + * {} + */ +export interface ListArtifactsRequest { + /** Page size. Defaults to 25 */ + limit?: number; + /** Opaque token from a previous response `next_page_token`. */ + pageToken?: string; + /** When set, only artifacts created in this session are returned. */ + createdBySessionId?: string; + /** Case-insensitive substring match on artifact title. */ + title?: string; +} diff --git a/packages/trueforge-sdk/src/api/resources/artifacts/client/requests/index.ts b/packages/trueforge-sdk/src/api/resources/artifacts/client/requests/index.ts new file mode 100644 index 0000000000..a83a129a26 --- /dev/null +++ b/packages/trueforge-sdk/src/api/resources/artifacts/client/requests/index.ts @@ -0,0 +1 @@ +export type { ListArtifactsRequest } from "./ListArtifactsRequest.js"; diff --git a/packages/trueforge-sdk/src/api/resources/artifacts/exports.ts b/packages/trueforge-sdk/src/api/resources/artifacts/exports.ts new file mode 100644 index 0000000000..8fe5f4af68 --- /dev/null +++ b/packages/trueforge-sdk/src/api/resources/artifacts/exports.ts @@ -0,0 +1,4 @@ +// This file was auto-generated by Fern from our API Definition. + +export { ArtifactsClient } from "./client/Client.js"; +export * from "./client/index.js"; diff --git a/packages/trueforge-sdk/src/api/resources/artifacts/index.ts b/packages/trueforge-sdk/src/api/resources/artifacts/index.ts new file mode 100644 index 0000000000..914b8c3c72 --- /dev/null +++ b/packages/trueforge-sdk/src/api/resources/artifacts/index.ts @@ -0,0 +1 @@ +export * from "./client/index.js"; diff --git a/packages/trueforge-sdk/src/api/resources/index.ts b/packages/trueforge-sdk/src/api/resources/index.ts index 8d86eb8ec8..11fd9df2e1 100644 --- a/packages/trueforge-sdk/src/api/resources/index.ts +++ b/packages/trueforge-sdk/src/api/resources/index.ts @@ -1,5 +1,7 @@ export * from "./agents/client/requests/index.js"; export * as agents from "./agents/index.js"; +export * from "./artifacts/client/requests/index.js"; +export * as artifacts from "./artifacts/index.js"; export * as auth from "./auth/index.js"; export * as catalogs from "./catalogs/index.js"; export * from "./internal/client/requests/index.js"; diff --git a/packages/trueforge-sdk/src/api/types/Artifact.ts b/packages/trueforge-sdk/src/api/types/Artifact.ts new file mode 100644 index 0000000000..965c19be67 --- /dev/null +++ b/packages/trueforge-sdk/src/api/types/Artifact.ts @@ -0,0 +1,14 @@ +// This file was auto-generated by Fern from our API Definition. + +import type * as TrueForge from "../index.js"; + +export interface Artifact { + createdAt: Date; + createdBySessionId: string; + createdBySubject: TrueForge.Subject; + /** Latest version. */ + latestVersion: number; + slug: string; + title: string; + updatedAt: Date; +} diff --git a/packages/trueforge-sdk/src/api/types/ListArtifactsResponse.ts b/packages/trueforge-sdk/src/api/types/ListArtifactsResponse.ts new file mode 100644 index 0000000000..f1a1d73d69 --- /dev/null +++ b/packages/trueforge-sdk/src/api/types/ListArtifactsResponse.ts @@ -0,0 +1,8 @@ +// This file was auto-generated by Fern from our API Definition. + +import type * as TrueForge from "../index.js"; + +export interface ListArtifactsResponse { + data: TrueForge.Artifact[]; + pagination: TrueForge.TokenPagination; +} diff --git a/packages/trueforge-sdk/src/api/types/index.ts b/packages/trueforge-sdk/src/api/types/index.ts index 846a4b5f26..ccf34864d0 100644 --- a/packages/trueforge-sdk/src/api/types/index.ts +++ b/packages/trueforge-sdk/src/api/types/index.ts @@ -11,6 +11,7 @@ export * from "./AnthropicModelProvider.js"; export * from "./ApprovalAllow.js"; export * from "./ApprovalDecision.js"; export * from "./ApprovalDeny.js"; +export * from "./Artifact.js"; export * from "./AskUserQuestionsConfig.js"; export * from "./AvailableMcpServer.js"; export * from "./AvailableModel.js"; @@ -103,6 +104,7 @@ export * from "./InputTokensCompactionTrigger.js"; export * from "./LargeToolResponseConfig.js"; export * from "./LegacyTurnInputItem.js"; export * from "./ListAgentsResponse.js"; +export * from "./ListArtifactsResponse.js"; export * from "./ListAvailableMcpServersResponse.js"; export * from "./ListAvailableModelsResponse.js"; export * from "./ListAvailableSkillsResponse.js"; diff --git a/packages/trueforge-sdk/src/serialization/types/Artifact.ts b/packages/trueforge-sdk/src/serialization/types/Artifact.ts new file mode 100644 index 0000000000..43c811fc7f --- /dev/null +++ b/packages/trueforge-sdk/src/serialization/types/Artifact.ts @@ -0,0 +1,29 @@ +// This file was auto-generated by Fern from our API Definition. + +import type * as TrueForge from "../../api/index.js"; +import * as core from "../../core/index.js"; +import type * as serializers from "../index.js"; +import { Subject } from "./Subject.js"; + +export const Artifact: core.serialization.ObjectSchema = + core.serialization.object({ + createdAt: core.serialization.property("created_at", core.serialization.date()), + createdBySessionId: core.serialization.property("created_by_session_id", core.serialization.string()), + createdBySubject: core.serialization.property("created_by_subject", Subject), + latestVersion: core.serialization.property("latest_version", core.serialization.number()), + slug: core.serialization.string(), + title: core.serialization.string(), + updatedAt: core.serialization.property("updated_at", core.serialization.date()), + }); + +export declare namespace Artifact { + export interface Raw { + created_at: string; + created_by_session_id: string; + created_by_subject: Subject.Raw; + latest_version: number; + slug: string; + title: string; + updated_at: string; + } +} diff --git a/packages/trueforge-sdk/src/serialization/types/ListArtifactsResponse.ts b/packages/trueforge-sdk/src/serialization/types/ListArtifactsResponse.ts new file mode 100644 index 0000000000..6f964c15e0 --- /dev/null +++ b/packages/trueforge-sdk/src/serialization/types/ListArtifactsResponse.ts @@ -0,0 +1,22 @@ +// This file was auto-generated by Fern from our API Definition. + +import type * as TrueForge from "../../api/index.js"; +import * as core from "../../core/index.js"; +import type * as serializers from "../index.js"; +import { Artifact } from "./Artifact.js"; +import { TokenPagination } from "./TokenPagination.js"; + +export const ListArtifactsResponse: core.serialization.ObjectSchema< + serializers.ListArtifactsResponse.Raw, + TrueForge.ListArtifactsResponse +> = core.serialization.object({ + data: core.serialization.list(Artifact), + pagination: TokenPagination, +}); + +export declare namespace ListArtifactsResponse { + export interface Raw { + data: Artifact.Raw[]; + pagination: TokenPagination.Raw; + } +} diff --git a/packages/trueforge-sdk/src/serialization/types/index.ts b/packages/trueforge-sdk/src/serialization/types/index.ts index 846a4b5f26..ccf34864d0 100644 --- a/packages/trueforge-sdk/src/serialization/types/index.ts +++ b/packages/trueforge-sdk/src/serialization/types/index.ts @@ -11,6 +11,7 @@ export * from "./AnthropicModelProvider.js"; export * from "./ApprovalAllow.js"; export * from "./ApprovalDecision.js"; export * from "./ApprovalDeny.js"; +export * from "./Artifact.js"; export * from "./AskUserQuestionsConfig.js"; export * from "./AvailableMcpServer.js"; export * from "./AvailableModel.js"; @@ -103,6 +104,7 @@ export * from "./InputTokensCompactionTrigger.js"; export * from "./LargeToolResponseConfig.js"; export * from "./LegacyTurnInputItem.js"; export * from "./ListAgentsResponse.js"; +export * from "./ListArtifactsResponse.js"; export * from "./ListAvailableMcpServersResponse.js"; export * from "./ListAvailableModelsResponse.js"; export * from "./ListAvailableSkillsResponse.js"; diff --git a/packages/trueforge-sdk/tests/wire/artifacts.test.ts b/packages/trueforge-sdk/tests/wire/artifacts.test.ts new file mode 100644 index 0000000000..69d91165e2 --- /dev/null +++ b/packages/trueforge-sdk/tests/wire/artifacts.test.ts @@ -0,0 +1,94 @@ +// This file was auto-generated by Fern from our API Definition. + +import * as TrueForgeTypes from "../../src/api/index"; +import { TrueForge } from "../../src/Client"; +import { mockServerPool } from "../mock-server/MockServerPool"; + +describe("ArtifactsClient", () => { + test("list (1)", async () => { + const server = mockServerPool.createServer(); + const client = new TrueForge({ maxRetries: 0, token: "test", baseUrl: server.baseUrl }); + + const rawResponseBody = { + data: [ + { + created_at: "2024-01-15T09:30:00Z", + created_by_session_id: "created_by_session_id", + created_by_subject: { + subject_display_name: "subject_display_name", + subject_id: "subject_id", + subject_type: "subject_type", + }, + latest_version: 1, + slug: "slug", + title: "title", + updated_at: "2024-01-15T09:30:00Z", + }, + ], + pagination: { limit: 1, next_page_token: "next_page_token", previous_page_token: "previous_page_token" }, + }; + + server + .mockEndpoint({ once: false }) + .get("/api/v1/artifacts") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const expected = { + data: [ + { + createdAt: new Date("2024-01-15T09:30:00.000Z"), + createdBySessionId: "created_by_session_id", + createdBySubject: { + subjectDisplayName: "subject_display_name", + subjectId: "subject_id", + subjectType: "subject_type", + }, + latestVersion: 1, + slug: "slug", + title: "title", + updatedAt: new Date("2024-01-15T09:30:00.000Z"), + }, + ], + pagination: { + limit: 1, + nextPageToken: "next_page_token", + previousPageToken: "previous_page_token", + }, + }; + const page = await client.artifacts.list(); + + expect(expected.data).toEqual(page.data); + expect(page.hasNextPage()).toBe(true); + const nextPage = await page.getNextPage(); + expect(expected.data).toEqual(nextPage.data); + }); + + test("list (2)", async () => { + const server = mockServerPool.createServer(); + const client = new TrueForge({ maxRetries: 0, token: "test", baseUrl: server.baseUrl }); + + const rawResponseBody = { error: { message: "message" } }; + + server.mockEndpoint().get("/api/v1/artifacts").respondWith().statusCode(400).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.artifacts.list(); + }).rejects.toThrow(TrueForgeTypes.BadRequestError); + }); + + test("list (3)", async () => { + const server = mockServerPool.createServer(); + const client = new TrueForge({ maxRetries: 0, token: "test", baseUrl: server.baseUrl }); + + const rawResponseBody = { error: { message: "message" } }; + + server.mockEndpoint().get("/api/v1/artifacts").respondWith().statusCode(401).jsonBody(rawResponseBody).build(); + + await expect(async () => { + return await client.artifacts.list(); + }).rejects.toThrow(TrueForgeTypes.UnauthorizedError); + }); +}); diff --git a/packages/trueforge/scripts/write-openapi.ts b/packages/trueforge/scripts/write-openapi.ts index a2deddf780..94749e6bd9 100644 --- a/packages/trueforge/scripts/write-openapi.ts +++ b/packages/trueforge/scripts/write-openapi.ts @@ -26,6 +26,7 @@ import configuration from '../src/config'; import { McpServerWithAuthStore } from '../src/db/McpServerWithAuthStore'; import { SqliteAccessControlStore } from '../src/db/sqlite/access-control-store/SqliteAccessControlStore'; import { SqliteAgentStore } from '../src/db/sqlite/agent-store/SqliteAgentStore'; +import { SqliteArtifactStore } from '../src/db/sqlite/artifact-store/SqliteArtifactStore'; import { createSqliteDb } from '../src/db/sqlite/client'; import { SqliteConfigurationStore } from '../src/db/sqlite/configuration-store/SqliteConfigurationStore'; import { SqliteMcpServerStore } from '../src/db/sqlite/mcp-server-store/SqliteMcpServerStore'; @@ -107,6 +108,7 @@ const app = createServerApp({ configurationStore, withTransaction: callback => db.transaction().execute(callback), scheduleStore: new SqliteScheduleStore(db), + artifactStore: new SqliteArtifactStore(db), tokenStore, sessionStore, accessControlStore: new SqliteAccessControlStore(db), diff --git a/packages/trueforge/src/apis/artifacts.ts b/packages/trueforge/src/apis/artifacts.ts new file mode 100644 index 0000000000..86540d9100 --- /dev/null +++ b/packages/trueforge/src/apis/artifacts.ts @@ -0,0 +1,51 @@ +import { OpenAPIHono, type RouteHandler } from '@hono/zod-openapi'; +import { InvalidPageTokenError } from '@truefoundry/trueforge-core/agent-session'; +import { HTTPException } from 'hono/http-exception'; +import type { ResolveRequestContext } from '../auth/identity'; +import type { ArtifactRecord, IArtifactStore } from '../db/artifactStore'; +import { listArtifactsRoute } from '../routes/artifactRoutes'; +import type { Artifact } from '../schemas/artifact'; + +export interface ArtifactsRouterDeps { + artifactStore: IArtifactStore; + resolveRequestContext: ResolveRequestContext; +} + +function toWireArtifact(record: ArtifactRecord): Artifact { + return { + slug: record.slug, + title: record.title, + latest_version: record.latest_version, + created_by_subject: record.created_by_subject, + created_by_session_id: record.created_by_session_id, + created_at: record.created_at, + updated_at: record.updated_at, + }; +} + +export function createArtifactsRouter(deps: ArtifactsRouterDeps) { + const listHandler: RouteHandler = async c => { + const query = c.req.valid('query'); + const requestContext = deps.resolveRequestContext(c); + try { + const { data, pagination } = await deps.artifactStore.listArtifacts({ + tenant_id: requestContext.tenant_id, + created_by_subject_id: requestContext.subject.id, + created_by_session_id: query.created_by_session_id, + title: query.title, + limit: query.limit, + page_token: query.page_token, + }); + return c.json({ data: data.map(toWireArtifact), pagination }, 200); + } catch (error) { + if (error instanceof InvalidPageTokenError) { + throw new HTTPException(400, { message: error.message, cause: error }); + } + throw error; + } + }; + + const router = new OpenAPIHono(); + router.openapi(listArtifactsRoute, listHandler); + return router; +} diff --git a/packages/trueforge/src/app.ts b/packages/trueforge/src/app.ts index c61daf9849..7cbe4b491f 100644 --- a/packages/trueforge/src/app.ts +++ b/packages/trueforge/src/app.ts @@ -11,6 +11,7 @@ import { randomUUID } from 'node:crypto'; import type { Configuration } from 'openid-client'; import type { Logger } from 'winston'; import { createAgentsRouter } from './apis/agents'; +import { createArtifactsRouter } from './apis/artifacts'; import { createAuthRouter } from './apis/auth'; import { createCapabilitiesRouter } from './apis/capabilities'; import { createCatalogRouter } from './apis/catalog'; @@ -52,6 +53,7 @@ import type { WebSearchCatalog } from './catalog/WebSearchCatalog'; import configuration, { getPublicUiBasePath, getTrueForgeAuthMode, TrueForgeAuthMode } from './config'; import type { IAccessControlStore } from './db/accessControlStore'; import type { AgentRecord, IAgentStore } from './db/agentStore'; +import type { IArtifactStore } from './db/artifactStore'; import type { IConfigurationStore } from './db/configurationStore'; import type { IMcpServerWithAuthStore } from './db/mcpServerStore'; import type { IMemoryProviderStore } from './db/memoryProviderStore'; @@ -341,6 +343,7 @@ export interface ServerDeps { /** DB singleton, or the env-backed shared store in TrueFoundry mode. */ sandboxProviderStore: ISandboxProviderStore; scheduleStore: IScheduleStore; + artifactStore: IArtifactStore; sessionMetricsStore: ISessionMetricsStore; sessions: Sessions; sessionStore: ISessionStore; @@ -555,6 +558,10 @@ export function createServerApp(deps: ServerDeps) { authMiddleware, ), ); + app.route( + '/api/v1/artifacts', + withAuth(createArtifactsRouter({ artifactStore: deps.artifactStore, resolveRequestContext }), authMiddleware), + ); // Registered before /api/v1/settings: tenant-wide switches are admin-gated in every mode, // while the catalog settings below stay closed in TrueFoundry mode. app.route( diff --git a/packages/trueforge/src/main.ts b/packages/trueforge/src/main.ts index 781474266c..37d99e68af 100644 --- a/packages/trueforge/src/main.ts +++ b/packages/trueforge/src/main.ts @@ -112,6 +112,7 @@ import { createController } from './controller'; import { memoryIngestFromConfig } from './controller/memoryIngest'; import type { IAccessControlStore } from './db/accessControlStore'; import type { IAgentStore } from './db/agentStore'; +import type { IArtifactStore } from './db/artifactStore'; import type { IConfigurationStore } from './db/configurationStore'; import type { IMcpServerWithAuthStore } from './db/mcpServerStore'; import { McpServerWithAuthStore } from './db/McpServerWithAuthStore'; @@ -165,6 +166,7 @@ interface ServerPersistence { accessControlStore: IAccessControlStore; /** extra pre-resolved stores for scheduled runs */ agentStore: IAgentStore; + artifactStore: IArtifactStore; destroyDb: () => Promise; mcpOAuthStore: IMcpServerWithAuthStore; /** Connected Redis (client + mode) for distributed peering; undefined in standalone. */ @@ -291,6 +293,7 @@ async function createStandalonePersistence(options: { import('./db/sqlite/schedule-store/SqliteScheduleStore'), import('./db/sqlite/sandbox-environment-store/SqliteSandboxEnvironmentStore'), import('./db/sqlite/access-control-store/SqliteAccessControlStore'), + import('./db/sqlite/artifact-store/SqliteArtifactStore'), ]), ]); const [ @@ -309,6 +312,7 @@ async function createStandalonePersistence(options: { { SqliteScheduleStore }, { SqliteSandboxEnvironmentStore }, { SqliteAccessControlStore }, + { SqliteArtifactStore }, ] = sqliteStores; const db = createSqliteDb(sqlitePath); @@ -342,6 +346,7 @@ async function createStandalonePersistence(options: { return { accessControlStore: new SqliteAccessControlStore(db), agentStore, + artifactStore: new SqliteArtifactStore(db), destroyDb: () => db.destroy(), mcpOAuthStore: mcpServerStore, redis: undefined, @@ -417,6 +422,7 @@ async function createDistributedPersistence(options: { import('./db/postgres/schedule-store/PostgresScheduleStore'), import('./db/postgres/sandbox-environment-store/PostgresSandboxEnvironmentStore'), import('./db/postgres/access-control-store/PostgresAccessControlStore'), + import('./db/postgres/artifact-store/PostgresArtifactStore'), ]), ]); const [ @@ -434,6 +440,7 @@ async function createDistributedPersistence(options: { { PostgresScheduleStore }, { PostgresSandboxEnvironmentStore }, { PostgresAccessControlStore }, + { PostgresArtifactStore }, ] = postgresStores; logger.info('Connecting to Postgres'); @@ -504,6 +511,7 @@ async function createDistributedPersistence(options: { return { accessControlStore: new PostgresAccessControlStore(db), agentStore, + artifactStore: new PostgresArtifactStore(db), destroyDb: () => db.destroy(), mcpOAuthStore: mcpServerWithAuthStore, redis: await connectRedis({ @@ -547,6 +555,7 @@ async function createServerRuntime(persistence: ServerPersistence< const { accessControlStore, agentStore, + artifactStore, destroyDb, mcpOAuthStore, redis, @@ -649,6 +658,7 @@ async function createServerRuntime(persistence: ServerPersistence< accessControlStore, activeTurns, agentStore, + artifactStore, authenticator, authorizer, eventSubscriptions, diff --git a/packages/trueforge/src/routes/artifactRoutes.ts b/packages/trueforge/src/routes/artifactRoutes.ts new file mode 100644 index 0000000000..7dbb2339fc --- /dev/null +++ b/packages/trueforge/src/routes/artifactRoutes.ts @@ -0,0 +1,38 @@ +/** + * Artifact route definitions (mounted at /api/v1/artifacts). + * Handlers are registered in apis/artifacts.ts. + */ +import { createRoute } from '@hono/zod-openapi'; +import { ListArtifactsRequestQuerySchema, ListArtifactsResponseSchema } from '../schemas/artifact'; +import { RequestErrorResponseSchema } from '../schemas/errors'; +import { TOKEN_PAGINATION } from './fernExtensions'; +import { OpenApiTag } from './openapiTags'; + +export const listArtifactsRoute = createRoute({ + method: 'get', + path: '/', + tags: [OpenApiTag.ARTIFACTS], + summary: 'List artifacts', + description: + 'List artifacts created by the caller, most recently updated first. Optionally filter by session, title substring, or `updated_at` range.', + 'x-fern-sdk-group-name': ['artifacts'], + 'x-fern-sdk-method-name': 'list', + 'x-fern-pagination': TOKEN_PAGINATION, + request: { + query: ListArtifactsRequestQuerySchema, + }, + responses: { + 200: { + content: { 'application/json': { schema: ListArtifactsResponseSchema } }, + description: 'Paginated artifacts.', + }, + 400: { + content: { 'application/json': { schema: RequestErrorResponseSchema } }, + description: 'Invalid query parameters or page token.', + }, + 401: { + content: { 'application/json': { schema: RequestErrorResponseSchema } }, + description: 'Unauthenticated.', + }, + }, +}); diff --git a/packages/trueforge/src/routes/openapiTags.ts b/packages/trueforge/src/routes/openapiTags.ts index dcf9790171..0c748d9a55 100644 --- a/packages/trueforge/src/routes/openapiTags.ts +++ b/packages/trueforge/src/routes/openapiTags.ts @@ -14,6 +14,7 @@ export enum OpenApiTag { AGENTS = 'Agents', SCHEDULES = 'Schedules', AGENT_SESSIONS = 'Agent Sessions', + ARTIFACTS = 'Artifacts', } /** Document-level tag order for `/api/v1/docs` and Mintlify. */ @@ -32,4 +33,5 @@ export const OPENAPI_DOCUMENT_TAGS: { name: OpenApiTag }[] = [ { name: OpenApiTag.AGENTS }, { name: OpenApiTag.SCHEDULES }, { name: OpenApiTag.AGENT_SESSIONS }, + { name: OpenApiTag.ARTIFACTS }, ]; diff --git a/packages/trueforge/src/schemas/artifact.ts b/packages/trueforge/src/schemas/artifact.ts new file mode 100644 index 0000000000..8c78c419b0 --- /dev/null +++ b/packages/trueforge/src/schemas/artifact.ts @@ -0,0 +1,45 @@ +import { z } from '@hono/zod-openapi'; +import { SubjectSchema, TokenPaginationSchema } from '@truefoundry/trueforge-core/agent-session'; +import { PAGE_LIMIT } from './common'; + +export const ArtifactSchema = z + .object({ + slug: z.string(), + title: z.string(), + latest_version: z.number().int().describe('Latest version.'), + created_by_subject: SubjectSchema, + created_by_session_id: z.string(), + created_at: z.iso.datetime(), + updated_at: z.iso.datetime(), + }) + .strict() + .openapi('Artifact'); + +export type Artifact = z.infer; + +export const ListArtifactsRequestQuerySchema = z + .object({ + limit: z.coerce + .number() + .int() + .min(1) + .max(PAGE_LIMIT) + .optional() + .default(PAGE_LIMIT) + .describe(`Page size. Defaults to ${String(PAGE_LIMIT)}`), + page_token: z.string().optional().describe('Opaque token from a previous response `next_page_token`.'), + created_by_session_id: z + .string() + .min(1) + .optional() + .describe('When set, only artifacts created in this session are returned.'), + title: z.string().trim().min(1).optional().describe('Case-insensitive substring match on artifact title.'), + }) + .openapi('ListArtifactsRequestQuery'); + +export const ListArtifactsResponseSchema = z + .object({ + data: z.array(ArtifactSchema), + pagination: TokenPaginationSchema, + }) + .openapi('ListArtifactsResponse'); diff --git a/packages/trueforge/tests/unit/apis/artifacts.test.ts b/packages/trueforge/tests/unit/apis/artifacts.test.ts new file mode 100644 index 0000000000..8f31b244e5 --- /dev/null +++ b/packages/trueforge/tests/unit/apis/artifacts.test.ts @@ -0,0 +1,61 @@ +import { createArtifactsRouter } from '../../../src/apis/artifacts'; +import { createdBySubjectFromRequestContext, STANDALONE_REQUEST_CONTEXT } from '../../../src/auth/identity'; +import { migrateSqliteToLatest } from '../../../src/db/migrateSqlite'; +import { SqliteArtifactStore } from '../../../src/db/sqlite/artifact-store/SqliteArtifactStore'; +import { createSqliteDb } from '../../../src/db/sqlite/client'; +import { ListArtifactsResponseSchema } from '../../../src/schemas/artifact'; +import { mountWithErrorHandler } from '../mountWithErrorHandler'; + +describe('artifacts router', () => { + let app: ReturnType; + + async function listTitles(query: string): Promise { + const response = await app.request(`/?${query}`); + expect(response.status).toBe(200); + return ListArtifactsResponseSchema.parse(await response.json()) + .data.map(a => a.title) + .sort(); + } + + beforeAll(async () => { + const db = createSqliteDb(':memory:'); + await migrateSqliteToLatest(db); + const artifactStore = new SqliteArtifactStore(db); + const mine = { + tenant_id: STANDALONE_REQUEST_CONTEXT.tenant_id, + created_by_subject: createdBySubjectFromRequestContext(STANDALONE_REQUEST_CONTEXT), + }; + await artifactStore.createArtifact({ ...mine, title: 'Q3 Report', created_by_session_id: 'session-1' }); + await artifactStore.createArtifact({ ...mine, title: 'Roadmap', created_by_session_id: 'session-2' }); + await artifactStore.createArtifact({ + ...mine, + title: 'not mine', + created_by_subject: { ...mine.created_by_subject, subject_id: 'someone-else' }, + created_by_session_id: 'session-1', + }); + app = mountWithErrorHandler( + createArtifactsRouter({ artifactStore, resolveRequestContext: () => STANDALONE_REQUEST_CONTEXT }), + ); + }); + + it("lists only the caller's artifacts with pagination", async () => { + const first = ListArtifactsResponseSchema.parse(await (await app.request('/?limit=1')).json()); + expect(first.data).toHaveLength(1); + const second = ListArtifactsResponseSchema.parse( + await (await app.request(`/?limit=1&page_token=${first.pagination.next_page_token ?? ''}`)).json(), + ); + expect([...first.data, ...second.data].map(a => a.title).sort()).toEqual(['Q3 Report', 'Roadmap']); + }); + + it('filters by created_by_session_id', async () => { + expect(await listTitles('created_by_session_id=session-2')).toEqual(['Roadmap']); + }); + + it('filters by title substring', async () => { + expect(await listTitles('title=report')).toEqual(['Q3 Report']); + }); + + it('rejects an invalid page token', async () => { + expect((await app.request('/?page_token=not-a-token')).status).toBe(400); + }); +}); diff --git a/python/trueforge_sdk/reference.md b/python/trueforge_sdk/reference.md index 20a21a712b..bd915fa166 100644 --- a/python/trueforge_sdk/reference.md +++ b/python/trueforge_sdk/reference.md @@ -497,6 +497,101 @@ client.agents.delete( + + + + +## Artifacts +
client.artifacts.list(...) -> ListArtifactsResponse +
+
+ +#### 📝 Description + +
+
+ +
+
+ +List artifacts created by the caller, most recently updated first. Optionally filter by session, title substring, or `updated_at` range. +
+
+
+
+ +#### 🔌 Usage + +
+
+ +
+
+ +```python +from trueforge_sdk import TrueForge + +client = TrueForge( + token="", + base_url="https://yourhost.com/path/to/api", +) + +client.artifacts.list() + +``` +
+
+
+
+ +#### ⚙️ Parameters + +
+
+ +
+
+ +**limit:** `typing.Optional[int]` — Page size. Defaults to 25 + +
+
+ +
+
+ +**page_token:** `typing.Optional[str]` — Opaque token from a previous response `next_page_token`. + +
+
+ +
+
+ +**created_by_session_id:** `typing.Optional[str]` — When set, only artifacts created in this session are returned. + +
+
+ +
+
+ +**title:** `typing.Optional[str]` — Case-insensitive substring match on artifact title. + +
+
+ +
+
+ +**request_options:** `typing.Optional[RequestOptions]` — Request-specific configuration. + +
+
+
+
+ +
diff --git a/python/trueforge_sdk/src/trueforge_sdk/__init__.py b/python/trueforge_sdk/src/trueforge_sdk/__init__.py index 9366c3bfe4..aeab071ebf 100644 --- a/python/trueforge_sdk/src/trueforge_sdk/__init__.py +++ b/python/trueforge_sdk/src/trueforge_sdk/__init__.py @@ -20,6 +20,7 @@ ApprovalAllow, ApprovalDecision, ApprovalDeny, + Artifact, AskUserQuestionsConfig, AvailableMcpServer, AvailableModel, @@ -112,6 +113,7 @@ LargeToolResponseConfig, LegacyTurnInputItem, ListAgentsResponse, + ListArtifactsResponse, ListAvailableMcpServersResponse, ListAvailableModelsResponse, ListAvailableSkillsResponse, @@ -322,6 +324,7 @@ ) from . import ( agents, + artifacts, auth, catalogs, internal, @@ -353,6 +356,7 @@ "ApprovalAllow": ".types", "ApprovalDecision": ".types", "ApprovalDeny": ".types", + "Artifact": ".types", "AskUserQuestionsConfig": ".types", "AsyncTrueForge": ".client", "AvailableMcpServer": ".types", @@ -458,6 +462,7 @@ "LargeToolResponseConfig": ".types", "LegacyTurnInputItem": ".types", "ListAgentsResponse": ".types", + "ListArtifactsResponse": ".types", "ListAvailableMcpServersResponse": ".types", "ListAvailableModelsResponse": ".types", "ListAvailableSkillsResponse": ".types", @@ -658,6 +663,7 @@ "ZepMemoryProviderAuth": ".types", "__version__": ".version", "agents": ".agents", + "artifacts": ".artifacts", "auth": ".auth", "catalogs": ".catalogs", "internal": ".internal", @@ -708,6 +714,7 @@ def __dir__(): "ApprovalAllow", "ApprovalDecision", "ApprovalDeny", + "Artifact", "AskUserQuestionsConfig", "AsyncTrueForge", "AvailableMcpServer", @@ -813,6 +820,7 @@ def __dir__(): "LargeToolResponseConfig", "LegacyTurnInputItem", "ListAgentsResponse", + "ListArtifactsResponse", "ListAvailableMcpServersResponse", "ListAvailableModelsResponse", "ListAvailableSkillsResponse", @@ -1013,6 +1021,7 @@ def __dir__(): "ZepMemoryProviderAuth", "__version__", "agents", + "artifacts", "auth", "catalogs", "internal", diff --git a/python/trueforge_sdk/src/trueforge_sdk/artifacts/__init__.py b/python/trueforge_sdk/src/trueforge_sdk/artifacts/__init__.py new file mode 100644 index 0000000000..5cde0202dc --- /dev/null +++ b/python/trueforge_sdk/src/trueforge_sdk/artifacts/__init__.py @@ -0,0 +1,4 @@ +# This file was auto-generated by Fern from our API Definition. + +# isort: skip_file + diff --git a/python/trueforge_sdk/src/trueforge_sdk/artifacts/client.py b/python/trueforge_sdk/src/trueforge_sdk/artifacts/client.py new file mode 100644 index 0000000000..1afadb1611 --- /dev/null +++ b/python/trueforge_sdk/src/trueforge_sdk/artifacts/client.py @@ -0,0 +1,165 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from ..core.pagination import AsyncPager, SyncPager +from ..core.request_options import RequestOptions +from ..types.artifact import Artifact +from ..types.list_artifacts_response import ListArtifactsResponse +from .raw_client import AsyncRawArtifactsClient, RawArtifactsClient + + +class ArtifactsClient: + def __init__(self, *, client_wrapper: SyncClientWrapper): + self._raw_client = RawArtifactsClient(client_wrapper=client_wrapper) + + @property + def with_raw_response(self) -> RawArtifactsClient: + """ + Retrieves a raw implementation of this client that returns raw responses. + + Returns + ------- + RawArtifactsClient + """ + return self._raw_client + + def list( + self, + *, + limit: typing.Optional[int] = 25, + page_token: typing.Optional[str] = None, + created_by_session_id: typing.Optional[str] = None, + title: typing.Optional[str] = None, + request_options: typing.Optional[RequestOptions] = None, + ) -> SyncPager[Artifact, ListArtifactsResponse]: + """ + List artifacts created by the caller, most recently updated first. Optionally filter by session, title substring, or `updated_at` range. + + Parameters + ---------- + limit : typing.Optional[int] + Page size. Defaults to 25 + + page_token : typing.Optional[str] + Opaque token from a previous response `next_page_token`. + + created_by_session_id : typing.Optional[str] + When set, only artifacts created in this session are returned. + + title : typing.Optional[str] + Case-insensitive substring match on artifact title. + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + SyncPager[Artifact, ListArtifactsResponse] + Paginated artifacts. + + Examples + -------- + from trueforge_sdk import TrueForge + + client = TrueForge( + token="YOUR_TOKEN", + base_url="https://yourhost.com/path/to/api", + ) + response = client.artifacts.list() + for item in response: + yield item + # alternatively, you can paginate page-by-page + for page in response.iter_pages(): + yield page + """ + return self._raw_client.list( + limit=limit, + page_token=page_token, + created_by_session_id=created_by_session_id, + title=title, + request_options=request_options, + ) + + +class AsyncArtifactsClient: + def __init__(self, *, client_wrapper: AsyncClientWrapper): + self._raw_client = AsyncRawArtifactsClient(client_wrapper=client_wrapper) + + @property + def with_raw_response(self) -> AsyncRawArtifactsClient: + """ + Retrieves a raw implementation of this client that returns raw responses. + + Returns + ------- + AsyncRawArtifactsClient + """ + return self._raw_client + + async def list( + self, + *, + limit: typing.Optional[int] = 25, + page_token: typing.Optional[str] = None, + created_by_session_id: typing.Optional[str] = None, + title: typing.Optional[str] = None, + request_options: typing.Optional[RequestOptions] = None, + ) -> AsyncPager[Artifact, ListArtifactsResponse]: + """ + List artifacts created by the caller, most recently updated first. Optionally filter by session, title substring, or `updated_at` range. + + Parameters + ---------- + limit : typing.Optional[int] + Page size. Defaults to 25 + + page_token : typing.Optional[str] + Opaque token from a previous response `next_page_token`. + + created_by_session_id : typing.Optional[str] + When set, only artifacts created in this session are returned. + + title : typing.Optional[str] + Case-insensitive substring match on artifact title. + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + AsyncPager[Artifact, ListArtifactsResponse] + Paginated artifacts. + + Examples + -------- + import asyncio + + from trueforge_sdk import AsyncTrueForge + + client = AsyncTrueForge( + token="YOUR_TOKEN", + base_url="https://yourhost.com/path/to/api", + ) + + + async def main() -> None: + response = await client.artifacts.list() + async for item in response: + yield item + + # alternatively, you can paginate page-by-page + async for page in response.iter_pages(): + yield page + + + asyncio.run(main()) + """ + return await self._raw_client.list( + limit=limit, + page_token=page_token, + created_by_session_id=created_by_session_id, + title=title, + request_options=request_options, + ) diff --git a/python/trueforge_sdk/src/trueforge_sdk/artifacts/raw_client.py b/python/trueforge_sdk/src/trueforge_sdk/artifacts/raw_client.py new file mode 100644 index 0000000000..08874d00fd --- /dev/null +++ b/python/trueforge_sdk/src/trueforge_sdk/artifacts/raw_client.py @@ -0,0 +1,228 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing +from json.decoder import JSONDecodeError + +from ..core.api_error import ApiError +from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper +from ..core.pagination import AsyncPager, SyncPager +from ..core.parse_error import ParsingError +from ..core.request_options import RequestOptions +from ..core.unchecked_base_model import construct_type +from ..errors.bad_request_error import BadRequestError +from ..errors.unauthorized_error import UnauthorizedError +from ..types.artifact import Artifact +from ..types.list_artifacts_response import ListArtifactsResponse +from ..types.request_error_response import RequestErrorResponse +from pydantic import ValidationError + + +class RawArtifactsClient: + def __init__(self, *, client_wrapper: SyncClientWrapper): + self._client_wrapper = client_wrapper + + def list( + self, + *, + limit: typing.Optional[int] = 25, + page_token: typing.Optional[str] = None, + created_by_session_id: typing.Optional[str] = None, + title: typing.Optional[str] = None, + request_options: typing.Optional[RequestOptions] = None, + ) -> SyncPager[Artifact, ListArtifactsResponse]: + """ + List artifacts created by the caller, most recently updated first. Optionally filter by session, title substring, or `updated_at` range. + + Parameters + ---------- + limit : typing.Optional[int] + Page size. Defaults to 25 + + page_token : typing.Optional[str] + Opaque token from a previous response `next_page_token`. + + created_by_session_id : typing.Optional[str] + When set, only artifacts created in this session are returned. + + title : typing.Optional[str] + Case-insensitive substring match on artifact title. + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + SyncPager[Artifact, ListArtifactsResponse] + Paginated artifacts. + """ + _response = self._client_wrapper.httpx_client.request( + "api/v1/artifacts", + method="GET", + params={ + "limit": limit, + "page_token": page_token, + "created_by_session_id": created_by_session_id, + "title": title, + }, + request_options=request_options, + ) + try: + if 200 <= _response.status_code < 300: + _parsed_response = typing.cast( + ListArtifactsResponse, + construct_type( + type_=ListArtifactsResponse, # type: ignore + object_=_response.json(), + ), + ) + _items = _parsed_response.data + _has_next = False + _get_next = None + if _parsed_response.pagination is not None: + _parsed_next = _parsed_response.pagination.next_page_token + _has_next = _parsed_next is not None and _parsed_next != "" + _get_next = lambda: self.list( + limit=limit, + page_token=_parsed_next, + created_by_session_id=created_by_session_id, + title=title, + request_options=request_options, + ) + return SyncPager(has_next=_has_next, items=_items, get_next=_get_next, response=_parsed_response) + if _response.status_code == 400: + raise BadRequestError( + headers=dict(_response.headers), + body=typing.cast( + RequestErrorResponse, + construct_type( + type_=RequestErrorResponse, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 401: + raise UnauthorizedError( + headers=dict(_response.headers), + body=typing.cast( + RequestErrorResponse, + construct_type( + type_=RequestErrorResponse, # type: ignore + object_=_response.json(), + ), + ), + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + except ValidationError as e: + raise ParsingError( + status_code=_response.status_code, headers=dict(_response.headers), body=_response.json(), cause=e + ) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) + + +class AsyncRawArtifactsClient: + def __init__(self, *, client_wrapper: AsyncClientWrapper): + self._client_wrapper = client_wrapper + + async def list( + self, + *, + limit: typing.Optional[int] = 25, + page_token: typing.Optional[str] = None, + created_by_session_id: typing.Optional[str] = None, + title: typing.Optional[str] = None, + request_options: typing.Optional[RequestOptions] = None, + ) -> AsyncPager[Artifact, ListArtifactsResponse]: + """ + List artifacts created by the caller, most recently updated first. Optionally filter by session, title substring, or `updated_at` range. + + Parameters + ---------- + limit : typing.Optional[int] + Page size. Defaults to 25 + + page_token : typing.Optional[str] + Opaque token from a previous response `next_page_token`. + + created_by_session_id : typing.Optional[str] + When set, only artifacts created in this session are returned. + + title : typing.Optional[str] + Case-insensitive substring match on artifact title. + + request_options : typing.Optional[RequestOptions] + Request-specific configuration. + + Returns + ------- + AsyncPager[Artifact, ListArtifactsResponse] + Paginated artifacts. + """ + _response = await self._client_wrapper.httpx_client.request( + "api/v1/artifacts", + method="GET", + params={ + "limit": limit, + "page_token": page_token, + "created_by_session_id": created_by_session_id, + "title": title, + }, + request_options=request_options, + ) + try: + if 200 <= _response.status_code < 300: + _parsed_response = typing.cast( + ListArtifactsResponse, + construct_type( + type_=ListArtifactsResponse, # type: ignore + object_=_response.json(), + ), + ) + _items = _parsed_response.data + _has_next = False + _get_next = None + if _parsed_response.pagination is not None: + _parsed_next = _parsed_response.pagination.next_page_token + _has_next = _parsed_next is not None and _parsed_next != "" + + async def _get_next(): + return await self.list( + limit=limit, + page_token=_parsed_next, + created_by_session_id=created_by_session_id, + title=title, + request_options=request_options, + ) + + return AsyncPager(has_next=_has_next, items=_items, get_next=_get_next, response=_parsed_response) + if _response.status_code == 400: + raise BadRequestError( + headers=dict(_response.headers), + body=typing.cast( + RequestErrorResponse, + construct_type( + type_=RequestErrorResponse, # type: ignore + object_=_response.json(), + ), + ), + ) + if _response.status_code == 401: + raise UnauthorizedError( + headers=dict(_response.headers), + body=typing.cast( + RequestErrorResponse, + construct_type( + type_=RequestErrorResponse, # type: ignore + object_=_response.json(), + ), + ), + ) + _response_json = _response.json() + except JSONDecodeError: + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text) + except ValidationError as e: + raise ParsingError( + status_code=_response.status_code, headers=dict(_response.headers), body=_response.json(), cause=e + ) + raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json) diff --git a/python/trueforge_sdk/src/trueforge_sdk/base_client.py b/python/trueforge_sdk/src/trueforge_sdk/base_client.py index aa6c162f93..d85e543a6f 100644 --- a/python/trueforge_sdk/src/trueforge_sdk/base_client.py +++ b/python/trueforge_sdk/src/trueforge_sdk/base_client.py @@ -10,6 +10,7 @@ if typing.TYPE_CHECKING: from .agents.client import AgentsClient, AsyncAgentsClient + from .artifacts.client import ArtifactsClient, AsyncArtifactsClient from .auth.client import AsyncAuthClient, AuthClient from .catalogs.client import AsyncCatalogsClient, CatalogsClient from .internal.client import AsyncInternalClient, InternalClient @@ -101,6 +102,7 @@ def __init__( ) self._internal: typing.Optional[InternalClient] = None self._agents: typing.Optional[AgentsClient] = None + self._artifacts: typing.Optional[ArtifactsClient] = None self._auth: typing.Optional[AuthClient] = None self._server: typing.Optional[ServerClient] = None self._mcp_servers: typing.Optional[McpServersClient] = None @@ -129,6 +131,14 @@ def agents(self): self._agents = AgentsClient(client_wrapper=self._client_wrapper) return self._agents + @property + def artifacts(self): + if self._artifacts is None: + from .artifacts.client import ArtifactsClient # noqa: E402 + + self._artifacts = ArtifactsClient(client_wrapper=self._client_wrapper) + return self._artifacts + @property def auth(self): if self._auth is None: @@ -316,6 +326,7 @@ def __init__( ) self._internal: typing.Optional[AsyncInternalClient] = None self._agents: typing.Optional[AsyncAgentsClient] = None + self._artifacts: typing.Optional[AsyncArtifactsClient] = None self._auth: typing.Optional[AsyncAuthClient] = None self._server: typing.Optional[AsyncServerClient] = None self._mcp_servers: typing.Optional[AsyncMcpServersClient] = None @@ -344,6 +355,14 @@ def agents(self): self._agents = AsyncAgentsClient(client_wrapper=self._client_wrapper) return self._agents + @property + def artifacts(self): + if self._artifacts is None: + from .artifacts.client import AsyncArtifactsClient # noqa: E402 + + self._artifacts = AsyncArtifactsClient(client_wrapper=self._client_wrapper) + return self._artifacts + @property def auth(self): if self._auth is None: diff --git a/python/trueforge_sdk/src/trueforge_sdk/types/__init__.py b/python/trueforge_sdk/src/trueforge_sdk/types/__init__.py index 2ce7a59229..0c672726a6 100644 --- a/python/trueforge_sdk/src/trueforge_sdk/types/__init__.py +++ b/python/trueforge_sdk/src/trueforge_sdk/types/__init__.py @@ -19,6 +19,7 @@ from .approval_allow import ApprovalAllow from .approval_decision import ApprovalDecision from .approval_deny import ApprovalDeny + from .artifact import Artifact from .ask_user_questions_config import AskUserQuestionsConfig from .available_mcp_server import AvailableMcpServer from .available_model import AvailableModel @@ -111,6 +112,7 @@ from .large_tool_response_config import LargeToolResponseConfig from .legacy_turn_input_item import LegacyTurnInputItem from .list_agents_response import ListAgentsResponse + from .list_artifacts_response import ListArtifactsResponse from .list_available_mcp_servers_response import ListAvailableMcpServersResponse from .list_available_models_response import ListAvailableModelsResponse from .list_available_skills_response import ListAvailableSkillsResponse @@ -318,6 +320,7 @@ "ApprovalAllow": ".approval_allow", "ApprovalDecision": ".approval_decision", "ApprovalDeny": ".approval_deny", + "Artifact": ".artifact", "AskUserQuestionsConfig": ".ask_user_questions_config", "AvailableMcpServer": ".available_mcp_server", "AvailableModel": ".available_model", @@ -410,6 +413,7 @@ "LargeToolResponseConfig": ".large_tool_response_config", "LegacyTurnInputItem": ".legacy_turn_input_item", "ListAgentsResponse": ".list_agents_response", + "ListArtifactsResponse": ".list_artifacts_response", "ListAvailableMcpServersResponse": ".list_available_mcp_servers_response", "ListAvailableModelsResponse": ".list_available_models_response", "ListAvailableSkillsResponse": ".list_available_skills_response", @@ -641,6 +645,7 @@ def __dir__(): "ApprovalAllow", "ApprovalDecision", "ApprovalDeny", + "Artifact", "AskUserQuestionsConfig", "AvailableMcpServer", "AvailableModel", @@ -733,6 +738,7 @@ def __dir__(): "LargeToolResponseConfig", "LegacyTurnInputItem", "ListAgentsResponse", + "ListArtifactsResponse", "ListAvailableMcpServersResponse", "ListAvailableModelsResponse", "ListAvailableSkillsResponse", diff --git a/python/trueforge_sdk/src/trueforge_sdk/types/artifact.py b/python/trueforge_sdk/src/trueforge_sdk/types/artifact.py new file mode 100644 index 0000000000..6b8b8ec40f --- /dev/null +++ b/python/trueforge_sdk/src/trueforge_sdk/types/artifact.py @@ -0,0 +1,31 @@ +# This file was auto-generated by Fern from our API Definition. + +import datetime as dt +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2 +from ..core.unchecked_base_model import UncheckedBaseModel +from .subject import Subject + + +class Artifact(UncheckedBaseModel): + created_at: dt.datetime + created_by_session_id: str + created_by_subject: Subject + latest_version: int = pydantic.Field() + """ + Latest version. + """ + + slug: str + title: str + updated_at: dt.datetime + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + else: + + class Config: + smart_union = True + extra = pydantic.Extra.allow diff --git a/python/trueforge_sdk/src/trueforge_sdk/types/list_artifacts_response.py b/python/trueforge_sdk/src/trueforge_sdk/types/list_artifacts_response.py new file mode 100644 index 0000000000..76433f054a --- /dev/null +++ b/python/trueforge_sdk/src/trueforge_sdk/types/list_artifacts_response.py @@ -0,0 +1,22 @@ +# This file was auto-generated by Fern from our API Definition. + +import typing + +import pydantic +from ..core.pydantic_utilities import IS_PYDANTIC_V2 +from ..core.unchecked_base_model import UncheckedBaseModel +from .artifact import Artifact +from .token_pagination import TokenPagination + + +class ListArtifactsResponse(UncheckedBaseModel): + data: typing.List[Artifact] + pagination: TokenPagination + + if IS_PYDANTIC_V2: + model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(extra="allow") # type: ignore # Pydantic v2 + else: + + class Config: + smart_union = True + extra = pydantic.Extra.allow