@agentforge-io/sdk-server 4.81.0 → 4.83.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/client.d.ts CHANGED
@@ -23,6 +23,7 @@ import { ReferenceResource } from './resources/reference';
23
23
  import { BusinessRolesResource } from './resources/business-roles';
24
24
  import { ToolsResource } from './resources/tools';
25
25
  import { BillingResource } from './resources/billing';
26
+ import { CreditResource } from './resources/credit';
26
27
  export interface AgentForgeClientOptions {
27
28
  /** Platform base URL — e.g. http://localhost:3032 in dev. */
28
29
  baseURL: string;
@@ -121,6 +122,8 @@ export declare class AgentForgeClient {
121
122
  readonly reference: ReferenceResource;
122
123
  /** PDK-BILLING — the installed tenant's plan, trial and subscription (use `af.forTenant(id).billing`). */
123
124
  readonly billing: BillingResource;
125
+ /** PDK-STORE-CREDIT — the business's customer accounts («fiado»): abonos, write-offs, statements. */
126
+ readonly credit: CreditResource;
124
127
  constructor(opts: AgentForgeClientOptions);
125
128
  /**
126
129
  * A client that acts inside `tenantId`, a tenant where this App is
package/dist/client.js CHANGED
@@ -45,6 +45,7 @@ const reference_1 = require("./resources/reference");
45
45
  const business_roles_1 = require("./resources/business-roles");
46
46
  const tools_1 = require("./resources/tools");
47
47
  const billing_1 = require("./resources/billing");
48
+ const credit_1 = require("./resources/credit");
48
49
  /** Header that selects an installed tenant for an App secret. */
49
50
  exports.INSTALLED_TENANT_HEADER = 'x-af-tenant';
50
51
  class AgentForgeClient {
@@ -96,6 +97,7 @@ class AgentForgeClient {
96
97
  this.catalog = new catalog_1.CatalogResource(this);
97
98
  this.reference = new reference_1.ReferenceResource(this);
98
99
  this.billing = new billing_1.BillingResource(this);
100
+ this.credit = new credit_1.CreditResource(this);
99
101
  }
100
102
  /**
101
103
  * A client that acts inside `tenantId`, a tenant where this App is
package/dist/errors.d.ts CHANGED
@@ -52,6 +52,18 @@ export declare class AgentForgeBillingError extends AgentForgeError {
52
52
  readonly code: AgentForgeBillingErrorCode;
53
53
  constructor(status: number, code: AgentForgeBillingErrorCode, message: string, body?: string);
54
54
  }
55
+ /**
56
+ * PDK-STORE-CREDIT — the coded refusals of `af.credit.*` and `af.cases.setOnAccount`. `code` narrows to this union.
57
+ * 404 `contact_not_found` / `not_found`; 409 `over_limit` / `account_blocked` / `already_charged` / `already_on_account` /
58
+ * `already_reversed` / `idempotency_conflict` (the key was used for a different request) / `payment_spent` /
59
+ * `account_merged`; 503 `ledger_guard_missing`; the rest 400. A refusal is final: do not retry it with another key.
60
+ */
61
+ export type AgentForgeCreditErrorCode = 'invalid_amount' | 'invalid_input' | 'contact_not_found' | 'account_blocked' | 'account_merged' | 'over_limit' | 'overpayment' | 'nothing_owed' | 'not_found' | 'already_reversed' | 'idempotency_conflict' | 'payment_spent' | 'exceeds_credit' | 'adjust_below_paid' | 'ledger_guard_missing' | 'wrong_kind' | 'already_charged' | 'contact_erased' | 'already_on_account' | 'fiado_needs_contact' | 'fiado_contact_mismatch' | 'contact_not_in_tenant' | 'fiado_needs_name_and_phone' | 'fiado_needs_total' | 'down_payment_covers_order';
62
+ export declare const AGENTFORGE_CREDIT_ERROR_CODES: readonly AgentForgeCreditErrorCode[];
63
+ export declare class AgentForgeCreditError extends AgentForgeError {
64
+ readonly code: AgentForgeCreditErrorCode;
65
+ constructor(status: number, code: AgentForgeCreditErrorCode, message: string, body?: string);
66
+ }
55
67
  export declare class AgentForgeNetworkError extends Error {
56
68
  readonly cause: Error;
57
69
  constructor(message: string, cause: Error);
package/dist/errors.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.AgentForgeNetworkError = exports.AgentForgeBillingError = exports.AGENTFORGE_BILLING_ERROR_CODES = exports.AgentForgeDuplicateContactError = exports.AgentForgeNotFoundError = exports.AgentForgeAuthError = exports.AgentForgeError = void 0;
3
+ exports.AgentForgeNetworkError = exports.AgentForgeCreditError = exports.AGENTFORGE_CREDIT_ERROR_CODES = exports.AgentForgeBillingError = exports.AGENTFORGE_BILLING_ERROR_CODES = exports.AgentForgeDuplicateContactError = exports.AgentForgeNotFoundError = exports.AgentForgeAuthError = exports.AgentForgeError = void 0;
4
4
  class AgentForgeError extends Error {
5
5
  constructor(status, message, body, code) {
6
6
  super(message);
@@ -103,6 +103,19 @@ class AgentForgeBillingError extends AgentForgeError {
103
103
  }
104
104
  }
105
105
  exports.AgentForgeBillingError = AgentForgeBillingError;
106
+ exports.AGENTFORGE_CREDIT_ERROR_CODES = [
107
+ 'invalid_amount', 'invalid_input', 'contact_not_found', 'account_blocked', 'account_merged', 'over_limit', 'overpayment',
108
+ 'nothing_owed', 'not_found', 'already_reversed', 'idempotency_conflict', 'payment_spent', 'exceeds_credit', 'adjust_below_paid',
109
+ 'ledger_guard_missing', 'wrong_kind', 'already_charged', 'contact_erased', 'already_on_account', 'fiado_needs_contact',
110
+ 'fiado_contact_mismatch', 'contact_not_in_tenant', 'fiado_needs_name_and_phone', 'fiado_needs_total', 'down_payment_covers_order',
111
+ ];
112
+ class AgentForgeCreditError extends AgentForgeError {
113
+ constructor(status, code, message, body) {
114
+ super(status, message, body, code);
115
+ this.name = 'AgentForgeCreditError';
116
+ }
117
+ }
118
+ exports.AgentForgeCreditError = AgentForgeCreditError;
106
119
  class AgentForgeNetworkError extends Error {
107
120
  constructor(message, cause) {
108
121
  super(message);
package/dist/index.d.ts CHANGED
@@ -1,12 +1,14 @@
1
1
  export { AgentForgeClient, INSTALLED_TENANT_HEADER } from './client';
2
2
  export type { AgentForgeClientOptions, RequestOptions } from './client';
3
- export { AgentForgeError, AgentForgeAuthError, AgentForgeNotFoundError, AgentForgeNetworkError, AgentForgeDuplicateContactError, AgentForgeBillingError, AGENTFORGE_BILLING_ERROR_CODES, } from './errors';
4
- export type { AgentForgeBillingErrorCode } from './errors';
3
+ export { AgentForgeError, AgentForgeAuthError, AgentForgeNotFoundError, AgentForgeNetworkError, AgentForgeDuplicateContactError, AgentForgeBillingError, AGENTFORGE_BILLING_ERROR_CODES, AgentForgeCreditError, AGENTFORGE_CREDIT_ERROR_CODES, } from './errors';
4
+ export type { AgentForgeBillingErrorCode, AgentForgeCreditErrorCode } from './errors';
5
+ export { CreditResource, CreditAccountsResource } from './resources/credit';
6
+ export type { CreditEntryKind, CreditAgingBucket, CreditAccountStatus, CreditEntry, CreditAllocation, CreditDebt, CreditAccount, CreditWriteResult, CreditStatementRow, CreditAccountListRow, CreditAccountsQuery, CreditAccountsPage, CreditStatementQuery, CreditStatement, UpdateCreditAccountInput, CreditPayInput, CreditReversePaymentInput, CreditWriteOffInput, CreditOpeningInput, CreditPayoutInput, } from './resources/credit';
5
7
  export { BillingResource } from './resources/billing';
6
8
  export type { BillingCurrency, BillingEntitlement, BillingEntitlementStatus, BillingInterval, BillingLimits, BillingPlan, BillingInvoice, BillingInvoicePage, BillingInvoicesQuery, BillingPaymentMethod, BillingCheckoutInput, BillingStartTrialInput, AppBillingWebhookEvent, AppBillingWebhookEventName, AppBillingWebhookData, } from './resources/billing';
7
9
  export { APP_WEBHOOK_HEADERS, TOOL_CALLBACK_HEADERS, ToolCallbackSignatureError, signToolCallbackPayload, verifyAppWebhook, verifyToolCallbackSignature, } from './webhooks';
8
10
  export { WebhookResource, type SetAppWebhookInput } from './resources/webhook';
9
- export type { AppWebhook, AppWebhookEvent, AppWebhookEventName, AppCaseWebhookEvent, AppCaseWebhookEventName, AppConversationMessageWebhookEvent, AppChannelStatusWebhookEvent, AgentMe, AgentSummary, AppUserConnectorStatus, ApprovalCopyBundle, ChannelContext, ChatStreamChunk, ChatStreamEvent, ChatTokenRecord, ConnectorDefaultsResult, ConnectorDefaultsSource, ConnectorResourceItem, ConnectorStatus, ConnectorToolInfo, ConversationHistory, ConversationStatus, CreateAgentInput, CreateClickupTaskInput, CreateClickupTaskResult, ExternalToolSummary, IssueChatTokenInput, ListAgentsResult, ListConnectorResourcesResult, McpServerConfig, MessageRecord, MessageRole, PublicAppBranding, PublicProfileBlock, PublicProfileTemplate, PublicTeamLanding, CreateTeamInput, UpdateTeamInput, TeamSummary, TeamDetail, TeamTheme, TeamBusinessHours, TeamWeekday, TeamProfileBlock, ProfileBlockPlacement, ProfileBlockPosition, CatalogBlockPreview, ServiceCta, ServiceCtaAction, CatalogServicesBlockConfig, AppInstallation, TemplateConfigField, TemplateSummary, TemplateDetail, TemplateInstallStats, TemplatePublisher, TemplateAuthor, AppTemplatePolicy, TemplateCategoryRef, MarketplaceCategory, MarketplaceCategoryGroup, MarketplaceLocale, TemplateInstallResult, CheckSystemTemplateResult, TemplatePublishIssue, UpsertSystemTemplateInput, UpsertSystemTemplateResult, TemplateReview, TemplateRatingSummary, TemplateReviewsPage, BusinessReview, BusinessReviewsPage, ProductRatingSummary, ProductReview, ProductReviewOwner, ProductReviewsPage, ProductReviewsOwnerPage, ListProductReviewsInput, ListProductReviewsForOwnerInput, HideProductReviewInput, ProductLikeResult, ReceiptReviewable, ReceiptReviewables, SaveReceiptReviewInput, ListTemplateReviewsInput, SaveTemplateReviewInput, TemplateReportKind, CreateTemplateReportInput, TenantConfigEntry, Place, PlaceSuggestion, SearchPlacesInput, AutocompletePlacesInput, PlacesScope, CaseField, CaseBusinessState, CaseType, CaseState, CaseStateType, CasePayment, CasePaymentAccount, CasePaymentStatus, CaseReceiptPayment, CaseDestination, CaseView, CaseContactLink, CaseStateStep, CreateDirectOrderInput, CreateOpenOrderInput, OpenOrderFreeLine, OpenOrderLineMark, OpenOrderPayment, CreateDirectBookingInput, MoveCaseSlotInput, CaseSlot, CatalogAttendedAt, CatalogBookingRule, CaseOrigin, CaseOriginChannel, DirectOrderForm, DirectPaymentOption, CaseClosingMethod, CaseClosingOrder, CaseClosingReport, CaseReportPage, CaseReceipt, CaseReceiptLine, CaseProposal, CaseProposalAnswer, CaseProposalChange, CaseProposalInput, ListCasesInput, AddressValue, DeliveryLocalPricing, DeliverySettings, PaymentMethodKind, PaymentSettings, PaymentSettingsInput, PaymentAccount, PaymentCountry, PaymentFieldDef, PaymentMethodDef, StructuredConfigInput, StructuredConfigEntry, DeliveryQuoteStatus, DeliveryQuoteInput, DeliveryPricePreview, DeliveryPricingPreview, DeliveryPricingPreviewInput, DeliveryRoute, DeliveryRouteInput, DeliveryQuote, AppSelf, AppOwner, AppSelfConnector, AppSelfConnectors, AppSelfConnectorTools, AppSelfConnectorToolsResponse, RegisterToolInput, RegisterToolsInput, BusinessRoleEntry, Catalog, CatalogCheckoutCta, CatalogCategory, CatalogProduct, CatalogProductPhoto, CatalogProductKind, CatalogProductStatus, CatalogPriceKind, CatalogAvailability, CatalogLockableField, CatalogProductPage, UpsertCatalogInput, CreateCatalogCategoryInput, ListCatalogCategoriesInput, UpdateCatalogCategoryInput, CreateCatalogProductInput, UpdateCatalogProductInput, ListCatalogProductsInput, CatalogPhotoUploadTarget, SignCatalogPhotoUploadInput, AttachCatalogPhotoInput, AttachCatalogCategoryImageInput, CatalogImportItem, CatalogImportPreview, CatalogImportApplyResult, CatalogFileMapping, CatalogFilePlan, CatalogFilePreview, CatalogFileApplyResult, CatalogFileInput, CatalogFilePreviewInput, CatalogMenuItem, CatalogMenuRead, CatalogMenuReadInput, CatalogMenuAttachInput, CatalogMenuChatFile, CatalogMenuKeepInSyncInput, CatalogMenuKeepInSyncResult, CatalogOption, CatalogOptionGroup, SaveCatalogOptionGroupInput, CatalogOptionChoice, CatalogOptionChange, CatalogOptionChangesPlan, CatalogUnit, SaveCatalogUnitInput, CatalogSaleRule, CatalogFileApplyInput, CatalogFileErrorCode, CatalogImportSourceStatus, CatalogImportColumnMapping, CatalogImportRunResult, CatalogImportSource, CreateCatalogImportSourceInput, UpdateCatalogImportSourceInput, PreviewCatalogImportSourceInput, CatalogImportSourcePreview, CatalogSheetTab, CatalogTemplateSheet, CreateCatalogTemplateSheetInput, ReferenceMatchItemInput, ReferenceMatchDecisionKind, ReferenceMatchCandidate, ReferenceMatchDecision, ReferenceMatchInput, ReferenceMatchResult, ReferenceProductInput, ReferenceProductsBulkInput, ReferenceProductsBulkResult, ReferenceProduct, ListReferenceProductsInput, ReferenceProductPage, GoogleCalendarAccount, GoogleCalendarEventInput, GoogleCalendarUpsertResult, GoogleCalendarBusyInput, GoogleCalendarBusyResult, GoogleSheetsPickerInput, GoogleSheetsPickerSession, GoogleSheetsPickerErrorCode, GoogleSheetsPickerResult, RegisterToolsResult, ToolCallbackPayload, ToolCallRecord, ToolPermission, ToolPermissionMode, TokenUsage, TenantSecretEntry, UpdateAgentInput, InboxThreadMode, InboxMessageDirection, InboxMessageSource, InboxMessageType, InboxThreadCustomerProfileView, InboxThreadView, InboxMessageView, SupportKpiTotals, SupportKpiResponse, AgentAttentionLogRow, } from './types';
11
+ export type { AppWebhook, AppWebhookEvent, AppWebhookEventName, AppCaseWebhookEvent, AppCaseWebhookEventName, AppConversationMessageWebhookEvent, AppChannelStatusWebhookEvent, AgentMe, AgentSummary, AppUserConnectorStatus, ApprovalCopyBundle, ChannelContext, ChatStreamChunk, ChatStreamEvent, ChatTokenRecord, ConnectorDefaultsResult, ConnectorDefaultsSource, ConnectorResourceItem, ConnectorStatus, ConnectorToolInfo, ConversationHistory, ConversationStatus, CreateAgentInput, CreateClickupTaskInput, CreateClickupTaskResult, ExternalToolSummary, IssueChatTokenInput, ListAgentsResult, ListConnectorResourcesResult, McpServerConfig, MessageRecord, MessageRole, PublicAppBranding, PublicProfileBlock, PublicProfileTemplate, PublicTeamLanding, CreateTeamInput, UpdateTeamInput, TeamSummary, TeamDetail, TeamTheme, TeamBusinessHours, TeamWeekday, TeamProfileBlock, ProfileBlockPlacement, ProfileBlockPosition, CatalogBlockPreview, ServiceCta, ServiceCtaAction, CatalogServicesBlockConfig, AppInstallation, TemplateConfigField, TemplateSummary, TemplateDetail, TemplateInstallStats, TemplatePublisher, TemplateAuthor, AppTemplatePolicy, TemplateCategoryRef, MarketplaceCategory, MarketplaceCategoryGroup, MarketplaceLocale, TemplateInstallResult, CheckSystemTemplateResult, TemplatePublishIssue, UpsertSystemTemplateInput, UpsertSystemTemplateResult, TemplateReview, TemplateRatingSummary, TemplateReviewsPage, BusinessReview, BusinessReviewsPage, ProductRatingSummary, ProductReview, ProductReviewOwner, ProductReviewsPage, ProductReviewsOwnerPage, ListProductReviewsInput, ListProductReviewsForOwnerInput, HideProductReviewInput, ProductLikeResult, ReceiptReviewable, ReceiptReviewables, SaveReceiptReviewInput, ListTemplateReviewsInput, SaveTemplateReviewInput, TemplateReportKind, CreateTemplateReportInput, TenantConfigEntry, Place, PlaceSuggestion, SearchPlacesInput, AutocompletePlacesInput, PlacesScope, CaseField, CaseBusinessState, CaseType, CaseState, CaseStateType, CasePayment, CasePaymentAccount, CasePaymentStatus, CaseReceiptPayment, CaseDestination, CaseView, CaseContactLink, CaseStateStep, CreateDirectOrderInput, CreateOpenOrderInput, OpenOrderFreeLine, OpenOrderLineMark, OpenOrderPayment, CreateDirectBookingInput, MoveCaseSlotInput, CaseSlot, CatalogAttendedAt, CatalogBookingRule, CaseOrigin, CaseOriginChannel, DirectOrderForm, DirectPaymentOption, CaseClosingMethod, CaseClosingOrder, CaseClosingReport, CaseClosingReceivables, CaseAccount, SetOnAccountInput, SetOnAccountResult, CaseReportPage, CaseReceipt, CaseReceiptLine, CaseProposal, CaseProposalAnswer, CaseProposalChange, CaseProposalInput, ListCasesInput, AddressValue, DeliveryLocalPricing, DeliverySettings, PaymentMethodKind, PaymentSettings, PaymentSettingsInput, PaymentAccount, PaymentCountry, PaymentFieldDef, PaymentMethodDef, StructuredConfigInput, StructuredConfigEntry, DeliveryQuoteStatus, DeliveryQuoteInput, DeliveryPricePreview, DeliveryPricingPreview, DeliveryPricingPreviewInput, DeliveryRoute, DeliveryRouteInput, DeliveryQuote, AppSelf, AppOwner, AppSelfConnector, AppSelfConnectors, AppSelfConnectorTools, AppSelfConnectorToolsResponse, RegisterToolInput, RegisterToolsInput, BusinessRoleEntry, Catalog, CatalogCheckoutCta, CatalogCategory, CatalogProduct, CatalogProductPhoto, CatalogProductKind, CatalogProductStatus, CatalogPriceKind, CatalogAvailability, CatalogLockableField, CatalogProductPage, UpsertCatalogInput, CreateCatalogCategoryInput, ListCatalogCategoriesInput, UpdateCatalogCategoryInput, CreateCatalogProductInput, UpdateCatalogProductInput, ListCatalogProductsInput, CatalogPhotoUploadTarget, SignCatalogPhotoUploadInput, AttachCatalogPhotoInput, AttachCatalogCategoryImageInput, CatalogImportItem, CatalogImportPreview, CatalogImportApplyResult, CatalogFileMapping, CatalogFilePlan, CatalogFilePreview, CatalogFileApplyResult, CatalogFileInput, CatalogFilePreviewInput, CatalogMenuItem, CatalogMenuRead, CatalogMenuReadInput, CatalogMenuAttachInput, CatalogMenuChatFile, CatalogMenuKeepInSyncInput, CatalogMenuKeepInSyncResult, CatalogOption, CatalogOptionGroup, SaveCatalogOptionGroupInput, CatalogOptionChoice, CatalogOptionChange, CatalogOptionChangesPlan, CatalogUnit, SaveCatalogUnitInput, CatalogSaleRule, CatalogFileApplyInput, CatalogFileErrorCode, CatalogImportSourceStatus, CatalogImportColumnMapping, CatalogImportRunResult, CatalogImportSource, CreateCatalogImportSourceInput, UpdateCatalogImportSourceInput, PreviewCatalogImportSourceInput, CatalogImportSourcePreview, CatalogSheetTab, CatalogTemplateSheet, CreateCatalogTemplateSheetInput, ReferenceMatchItemInput, ReferenceMatchDecisionKind, ReferenceMatchCandidate, ReferenceMatchDecision, ReferenceMatchInput, ReferenceMatchResult, ReferenceProductInput, ReferenceProductsBulkInput, ReferenceProductsBulkResult, ReferenceProduct, ListReferenceProductsInput, ReferenceProductPage, GoogleCalendarAccount, GoogleCalendarEventInput, GoogleCalendarUpsertResult, GoogleCalendarBusyInput, GoogleCalendarBusyResult, GoogleSheetsPickerInput, GoogleSheetsPickerSession, GoogleSheetsPickerErrorCode, GoogleSheetsPickerResult, RegisterToolsResult, ToolCallbackPayload, ToolCallRecord, ToolPermission, ToolPermissionMode, TokenUsage, TenantSecretEntry, UpdateAgentInput, InboxThreadMode, InboxMessageDirection, InboxMessageSource, InboxMessageType, InboxThreadCustomerProfileView, InboxThreadView, InboxMessageView, SupportKpiTotals, SupportKpiResponse, AgentAttentionLogRow, } from './types';
10
12
  export { AgentsResource } from './resources/agents';
11
13
  export { AnalyticsResource } from './resources/analytics';
12
14
  export type { GetSupportKpisInput, GetAgentAttentionLogInput, } from './resources/analytics';
@@ -33,7 +35,7 @@ export { DeliveryResource } from './resources/delivery';
33
35
  export { CasesResource } from './resources/cases';
34
36
  export { BusinessRolesResource } from './resources/business-roles';
35
37
  export { CatalogResource, CatalogCategoriesResource, CatalogProductsResource, CatalogProductReviewsResource, CatalogProductLikesResource, CatalogReviewsResource, CatalogPhotosResource, CatalogImportResource, CatalogFileImportResource, CatalogMenuImportResource, CatalogOptionGroupsResource, CatalogUnitsResource, CatalogSourcesResource, AgentForgeCatalogImportLimitError, CATALOG_IMPORT_MAX_ITEMS, } from './resources/catalog';
36
- export type { ListThreadsOptions, ListNewestMessagesOptions, NewestMessagesPage, SendMessageInput, AssignThreadInput, UnassignThreadInput, SetThreadModeInput, CloseThreadInput, } from './resources/inbox';
38
+ export type { ListThreadsOptions, ListNewestMessagesOptions, NewestMessagesPage, SendMessageInput, InboxOperatorAttachment, InboxAttachmentKind, AssignThreadInput, UnassignThreadInput, SetThreadModeInput, CloseThreadInput, } from './resources/inbox';
37
39
  export { ProvisioningResource } from './resources/provisioning';
38
40
  export type { ProvisionedTenant, ProvisionedApp, ProvisionedTeam, } from './resources/provisioning';
39
41
  export { SecretsResource } from './resources/secrets';
package/dist/index.js CHANGED
@@ -28,8 +28,8 @@
28
28
  // const payload = af.tools.verifyCallback({ rawBody, signatureHeader, secretPlaintext });
29
29
  // await af.tools.respondToCallback({ resultUrl: payload.resultUrl, tenantId: payload.tenantId, secret, result });
30
30
  Object.defineProperty(exports, "__esModule", { value: true });
31
- exports.CatalogProductLikesResource = exports.CatalogProductReviewsResource = exports.CatalogProductsResource = exports.CatalogCategoriesResource = exports.CatalogResource = exports.BusinessRolesResource = exports.CasesResource = exports.DeliveryResource = exports.FilesResource = exports.ContactListsResource = exports.ContactTagsResource = exports.ContactAddressesResource = exports.ContactVerificationResource = exports.ContactsResource = exports.PlacesResource = exports.TenantConfigResource = exports.MarketplaceResource = exports.REFERENCE_BULK_MAX_ITEMS = exports.REFERENCE_MATCH_MAX_ITEMS = exports.AgentForgeReferenceLimitError = exports.ReferenceProductsResource = exports.ReferenceResource = exports.TemplateReportsResource = exports.TemplateReviewsResource = exports.TemplatesResource = exports.InstallationsResource = exports.InboxResource = exports.parseGoogleSheetsPickerResult = exports.ConnectorsResource = exports.ChatResource = exports.AppsResource = exports.AnalyticsResource = exports.AgentsResource = exports.WebhookResource = exports.verifyToolCallbackSignature = exports.verifyAppWebhook = exports.signToolCallbackPayload = exports.ToolCallbackSignatureError = exports.TOOL_CALLBACK_HEADERS = exports.APP_WEBHOOK_HEADERS = exports.BillingResource = exports.AGENTFORGE_BILLING_ERROR_CODES = exports.AgentForgeBillingError = exports.AgentForgeDuplicateContactError = exports.AgentForgeNetworkError = exports.AgentForgeNotFoundError = exports.AgentForgeAuthError = exports.AgentForgeError = exports.INSTALLED_TENANT_HEADER = exports.AgentForgeClient = void 0;
32
- exports.ToolsResource = exports.TeamsResource = exports.SecretsResource = exports.ProvisioningResource = exports.CATALOG_IMPORT_MAX_ITEMS = exports.AgentForgeCatalogImportLimitError = exports.CatalogSourcesResource = exports.CatalogUnitsResource = exports.CatalogOptionGroupsResource = exports.CatalogMenuImportResource = exports.CatalogFileImportResource = exports.CatalogImportResource = exports.CatalogPhotosResource = exports.CatalogReviewsResource = void 0;
31
+ exports.CatalogResource = exports.BusinessRolesResource = exports.CasesResource = exports.DeliveryResource = exports.FilesResource = exports.ContactListsResource = exports.ContactTagsResource = exports.ContactAddressesResource = exports.ContactVerificationResource = exports.ContactsResource = exports.PlacesResource = exports.TenantConfigResource = exports.MarketplaceResource = exports.REFERENCE_BULK_MAX_ITEMS = exports.REFERENCE_MATCH_MAX_ITEMS = exports.AgentForgeReferenceLimitError = exports.ReferenceProductsResource = exports.ReferenceResource = exports.TemplateReportsResource = exports.TemplateReviewsResource = exports.TemplatesResource = exports.InstallationsResource = exports.InboxResource = exports.parseGoogleSheetsPickerResult = exports.ConnectorsResource = exports.ChatResource = exports.AppsResource = exports.AnalyticsResource = exports.AgentsResource = exports.WebhookResource = exports.verifyToolCallbackSignature = exports.verifyAppWebhook = exports.signToolCallbackPayload = exports.ToolCallbackSignatureError = exports.TOOL_CALLBACK_HEADERS = exports.APP_WEBHOOK_HEADERS = exports.BillingResource = exports.CreditAccountsResource = exports.CreditResource = exports.AGENTFORGE_CREDIT_ERROR_CODES = exports.AgentForgeCreditError = exports.AGENTFORGE_BILLING_ERROR_CODES = exports.AgentForgeBillingError = exports.AgentForgeDuplicateContactError = exports.AgentForgeNetworkError = exports.AgentForgeNotFoundError = exports.AgentForgeAuthError = exports.AgentForgeError = exports.INSTALLED_TENANT_HEADER = exports.AgentForgeClient = void 0;
32
+ exports.ToolsResource = exports.TeamsResource = exports.SecretsResource = exports.ProvisioningResource = exports.CATALOG_IMPORT_MAX_ITEMS = exports.AgentForgeCatalogImportLimitError = exports.CatalogSourcesResource = exports.CatalogUnitsResource = exports.CatalogOptionGroupsResource = exports.CatalogMenuImportResource = exports.CatalogFileImportResource = exports.CatalogImportResource = exports.CatalogPhotosResource = exports.CatalogReviewsResource = exports.CatalogProductLikesResource = exports.CatalogProductReviewsResource = exports.CatalogProductsResource = exports.CatalogCategoriesResource = void 0;
33
33
  var client_1 = require("./client");
34
34
  Object.defineProperty(exports, "AgentForgeClient", { enumerable: true, get: function () { return client_1.AgentForgeClient; } });
35
35
  Object.defineProperty(exports, "INSTALLED_TENANT_HEADER", { enumerable: true, get: function () { return client_1.INSTALLED_TENANT_HEADER; } });
@@ -41,6 +41,11 @@ Object.defineProperty(exports, "AgentForgeNetworkError", { enumerable: true, get
41
41
  Object.defineProperty(exports, "AgentForgeDuplicateContactError", { enumerable: true, get: function () { return errors_1.AgentForgeDuplicateContactError; } });
42
42
  Object.defineProperty(exports, "AgentForgeBillingError", { enumerable: true, get: function () { return errors_1.AgentForgeBillingError; } });
43
43
  Object.defineProperty(exports, "AGENTFORGE_BILLING_ERROR_CODES", { enumerable: true, get: function () { return errors_1.AGENTFORGE_BILLING_ERROR_CODES; } });
44
+ Object.defineProperty(exports, "AgentForgeCreditError", { enumerable: true, get: function () { return errors_1.AgentForgeCreditError; } });
45
+ Object.defineProperty(exports, "AGENTFORGE_CREDIT_ERROR_CODES", { enumerable: true, get: function () { return errors_1.AGENTFORGE_CREDIT_ERROR_CODES; } });
46
+ var credit_1 = require("./resources/credit");
47
+ Object.defineProperty(exports, "CreditResource", { enumerable: true, get: function () { return credit_1.CreditResource; } });
48
+ Object.defineProperty(exports, "CreditAccountsResource", { enumerable: true, get: function () { return credit_1.CreditAccountsResource; } });
44
49
  var billing_1 = require("./resources/billing");
45
50
  Object.defineProperty(exports, "BillingResource", { enumerable: true, get: function () { return billing_1.BillingResource; } });
46
51
  var webhooks_1 = require("./webhooks");
@@ -1,5 +1,5 @@
1
1
  import type { AgentForgeClient } from '../client';
2
- import type { CaseClosingReport, CaseProposalAnswer, CaseProposalInput, CaseReportPage, CasePaymentStatus, CaseReceipt, CaseState, CaseView, CreateDirectBookingInput, CreateDirectOrderInput, CreateOpenOrderInput, DirectOrderForm, ListCasesInput, MoveCaseSlotInput, ProductReview, ReceiptReviewables, SaveReceiptReviewInput } from '../types';
2
+ import type { CaseAccount, CaseClosingReport, CaseProposalAnswer, CaseProposalInput, CaseReportPage, CasePaymentStatus, CaseReceipt, CaseState, CaseView, CreateDirectBookingInput, CreateDirectOrderInput, CreateOpenOrderInput, DirectOrderForm, ListCasesInput, MoveCaseSlotInput, ProductReview, ReceiptReviewables, SaveReceiptReviewInput, SetOnAccountInput, SetOnAccountResult } from '../types';
3
3
  export declare class CasesResource {
4
4
  private readonly client;
5
5
  constructor(client: AgentForgeClient);
@@ -9,10 +9,16 @@ export declare class CasesResource {
9
9
  * `GET /api/v1/cases/reports/closing` — AGF-CASH-REGISTER: a closing between two
10
10
  * instants, (`from`, `to`], so consecutive closings never count a payment twice
11
11
  * nor miss one. 400 on a bad range; at most 400 days.
12
+ *
13
+ * PDK-STORE-CREDIT — `clampToClock: true` for a caller that chains closings (stores the returned `to` and starts the
14
+ * next from it): when its `to` is ahead of the platform's clock the report ends at the platform's clock, `to` says so
15
+ * and `requestedTo` is what was asked. Without it the request and the range are exactly what they always were. 400 when
16
+ * `from` itself is ahead of the platform's clock. An older platform ignores the flag.
12
17
  */
13
18
  closingReport(input: {
14
19
  from: string | Date;
15
20
  to: string | Date;
21
+ clampToClock?: boolean;
16
22
  }): Promise<CaseClosingReport>;
17
23
  /**
18
24
  * `GET /api/v1/cases/reports/orders` — AGF-CASH-REGISTER: the cases sent between two
@@ -174,6 +180,22 @@ export declare class CasesResource {
174
180
  amountCents?: number;
175
181
  accountId?: string;
176
182
  }): Promise<CaseView>;
183
+ /**
184
+ * `POST /api/v1/cases/:id/payment/on-account` — PDK-STORE-CREDIT «Dejar como fiado»: status `on_account` and the ledger
185
+ * charge in one transaction, optionally with a down payment. Business only, after acceptance, with a contact that has a
186
+ * name and a phone, and a known total > 0. A retried `idempotencyKey` returns the same result (`replayed: true`); the
187
+ * SDK never retries by itself and never makes up a key. Refusals throw `AgentForgeCreditError` (`err.code`):
188
+ * 400 `fiado_needs_contact` / `fiado_contact_mismatch` / `contact_not_in_tenant` / `contact_erased` /
189
+ * `fiado_needs_name_and_phone` / `fiado_needs_total` / `down_payment_covers_order` / `invalid_amount`;
190
+ * 409 `over_limit` / `account_blocked` / `already_on_account` / `already_charged` / `idempotency_conflict` / `account_merged`.
191
+ * A refusal without a code (not accepted yet, the case ended undone) stays a plain `AgentForgeError`.
192
+ */
193
+ setOnAccount(caseId: string, input: SetOnAccountInput): Promise<SetOnAccountResult>;
194
+ /**
195
+ * `GET /api/v1/cases/:id/account` — PDK-STORE-CREDIT: what ONE order owes on the customer account (for its receipt),
196
+ * never the account itself. `{ onAccount: false, payments: [] }` for an order that is not on account.
197
+ */
198
+ account(caseId: string): Promise<CaseAccount>;
177
199
  /**
178
200
  * `POST /api/v1/cases/:id/payment/method` — AGF-PAYMENT-METHOD-BUSINESS: the business
179
201
  * sets or changes how the customer pays (an `accountId` of `directForm().payment.options`;
@@ -5,6 +5,7 @@
5
5
  // business states of their type.
6
6
  Object.defineProperty(exports, "__esModule", { value: true });
7
7
  exports.CasesResource = void 0;
8
+ const credit_1 = require("./credit");
8
9
  class CasesResource {
9
10
  constructor(client) {
10
11
  this.client = client;
@@ -38,10 +39,17 @@ class CasesResource {
38
39
  * `GET /api/v1/cases/reports/closing` — AGF-CASH-REGISTER: a closing between two
39
40
  * instants, (`from`, `to`], so consecutive closings never count a payment twice
40
41
  * nor miss one. 400 on a bad range; at most 400 days.
42
+ *
43
+ * PDK-STORE-CREDIT — `clampToClock: true` for a caller that chains closings (stores the returned `to` and starts the
44
+ * next from it): when its `to` is ahead of the platform's clock the report ends at the platform's clock, `to` says so
45
+ * and `requestedTo` is what was asked. Without it the request and the range are exactly what they always were. 400 when
46
+ * `from` itself is ahead of the platform's clock. An older platform ignores the flag.
41
47
  */
42
48
  async closingReport(input) {
43
49
  const at = (v) => (v instanceof Date ? v.toISOString() : v);
44
50
  const qs = new URLSearchParams({ from: at(input.from), to: at(input.to) });
51
+ if (input.clampToClock)
52
+ qs.set('clampToClock', 'true');
45
53
  return this.client.request('GET', `/api/v1/cases/reports/closing?${qs}`);
46
54
  }
47
55
  /**
@@ -247,6 +255,31 @@ class CasesResource {
247
255
  ...(opts.accountId ? { accountId: opts.accountId } : {}),
248
256
  });
249
257
  }
258
+ /**
259
+ * `POST /api/v1/cases/:id/payment/on-account` — PDK-STORE-CREDIT «Dejar como fiado»: status `on_account` and the ledger
260
+ * charge in one transaction, optionally with a down payment. Business only, after acceptance, with a contact that has a
261
+ * name and a phone, and a known total > 0. A retried `idempotencyKey` returns the same result (`replayed: true`); the
262
+ * SDK never retries by itself and never makes up a key. Refusals throw `AgentForgeCreditError` (`err.code`):
263
+ * 400 `fiado_needs_contact` / `fiado_contact_mismatch` / `contact_not_in_tenant` / `contact_erased` /
264
+ * `fiado_needs_name_and_phone` / `fiado_needs_total` / `down_payment_covers_order` / `invalid_amount`;
265
+ * 409 `over_limit` / `account_blocked` / `already_on_account` / `already_charged` / `idempotency_conflict` / `account_merged`.
266
+ * A refusal without a code (not accepted yet, the case ended undone) stays a plain `AgentForgeError`.
267
+ */
268
+ async setOnAccount(caseId, input) {
269
+ try {
270
+ return await this.client.request('POST', `/api/v1/cases/${encodeURIComponent(caseId)}/payment/on-account`, input);
271
+ }
272
+ catch (err) {
273
+ throw (0, credit_1.asCreditError)(err);
274
+ }
275
+ }
276
+ /**
277
+ * `GET /api/v1/cases/:id/account` — PDK-STORE-CREDIT: what ONE order owes on the customer account (for its receipt),
278
+ * never the account itself. `{ onAccount: false, payments: [] }` for an order that is not on account.
279
+ */
280
+ async account(caseId) {
281
+ return this.client.request('GET', `/api/v1/cases/${encodeURIComponent(caseId)}/account`);
282
+ }
250
283
  /**
251
284
  * `POST /api/v1/cases/:id/payment/method` — AGF-PAYMENT-METHOD-BUSINESS: the business
252
285
  * sets or changes how the customer pays (an `accountId` of `directForm().payment.options`;
@@ -0,0 +1,205 @@
1
+ import type { AgentForgeClient } from '../client';
2
+ /** A credit-coded failure becomes the typed error; anything else (auth, network, an uncoded 404) is rethrown as is. */
3
+ export declare function asCreditError(err: unknown): unknown;
4
+ export type CreditEntryKind = 'charge' | 'payment' | 'charge_adjust' | 'charge_reversal' | 'opening' | 'write_off' | 'payment_reversal' | 'payout' | 'transfer';
5
+ export type CreditAgingBucket = 'current' | 'd1_30' | 'd31_60' | 'd61_plus';
6
+ export type CreditAccountStatus = 'active' | 'blocked' | 'merged';
7
+ export interface CreditEntry {
8
+ id: string;
9
+ seq: number;
10
+ accountId: string;
11
+ kind: CreditEntryKind;
12
+ /** + the customer owes more, − owes less. */
13
+ deltaCents: number;
14
+ caseId: string | null;
15
+ /** The order's short code as the business names it (absent on an older platform; only in the statement). */
16
+ caseCode?: string | null;
17
+ method: string | null;
18
+ paymentSnapshot: Record<string, unknown> | null;
19
+ reference: string | null;
20
+ note: string | null;
21
+ dueOn: string | null;
22
+ reversesId: string | null;
23
+ chargeId: string | null;
24
+ groupId: string | null;
25
+ sourceAt: string | null;
26
+ actor: string | null;
27
+ /** Server instant, ISO-8601 UTC with microseconds. */
28
+ occurredAt: string;
29
+ idempotencyKey: string;
30
+ }
31
+ export interface CreditAllocation {
32
+ id: string;
33
+ accountId: string;
34
+ sourceEntryId: string;
35
+ targetEntryId: string;
36
+ /** Signed: a reversal inserts negatives. */
37
+ cents: number;
38
+ causeEntryId: string;
39
+ }
40
+ export interface CreditDebt {
41
+ entryId: string;
42
+ kind: CreditEntryKind;
43
+ caseId: string | null;
44
+ /** The order's short code as the business names it (absent on an older platform). */
45
+ caseCode?: string | null;
46
+ totalCents: number;
47
+ outstandingCents: number;
48
+ dueOn: string | null;
49
+ chargedAt: string;
50
+ daysOverdue: number;
51
+ bucket: CreditAgingBucket;
52
+ }
53
+ export interface CreditAccount {
54
+ /** Null for a contact that never had an account (everything 0). */
55
+ accountId: string | null;
56
+ contactId: string;
57
+ status: CreditAccountStatus;
58
+ currency: string;
59
+ limitCents: number | null;
60
+ balanceCents: number;
61
+ owingCents: number;
62
+ /** Balance in the customer's favour (a reversal after paying): can be applied or paid out. */
63
+ creditCents: number;
64
+ debts: CreditDebt[];
65
+ }
66
+ /** What every write returns; a replay returns the SAME content with `replayed: true`. */
67
+ export interface CreditWriteResult {
68
+ replayed: boolean;
69
+ entries: CreditEntry[];
70
+ allocations: CreditAllocation[];
71
+ balanceCents: number;
72
+ accountId: string;
73
+ }
74
+ export interface CreditStatementRow extends CreditEntry {
75
+ /** The account's balance AFTER this row. */
76
+ runningBalanceCents: number;
77
+ }
78
+ export interface CreditAccountListRow {
79
+ accountId: string;
80
+ contactId: string;
81
+ displayName: string | null;
82
+ phone: string | null;
83
+ status: CreditAccountStatus;
84
+ balanceCents: number;
85
+ limitCents: number | null;
86
+ oldestOverdueDays: number;
87
+ aging: Record<CreditAgingBucket, number>;
88
+ }
89
+ export interface CreditAccountsQuery {
90
+ /** Default true: only accounts that owe. `false` lists all. */
91
+ owing?: boolean;
92
+ /** Only those with a debt past its due date. */
93
+ overdue?: boolean;
94
+ /** Matches the contact's name or phone. */
95
+ q?: string;
96
+ cursor?: string;
97
+ /** 1–100, default 50. */
98
+ limit?: number;
99
+ }
100
+ export interface CreditAccountsPage {
101
+ rows: CreditAccountListRow[];
102
+ nextCursor: string | null;
103
+ }
104
+ export interface CreditStatementQuery {
105
+ /** 1–200, default 50. */
106
+ limit?: number;
107
+ /** Pages backwards: pass the previous page's `nextBeforeSeq`. */
108
+ beforeSeq?: number;
109
+ }
110
+ export interface CreditStatement {
111
+ /** Newest first. */
112
+ rows: CreditStatementRow[];
113
+ nextBeforeSeq: number | null;
114
+ allocations: CreditAllocation[];
115
+ }
116
+ export interface UpdateCreditAccountInput {
117
+ status?: 'active' | 'blocked';
118
+ /** Whole cents, or `null` for no limit. */
119
+ limitCents?: number | null;
120
+ }
121
+ /** Fields every write takes. */
122
+ interface CreditWriteBase {
123
+ /** 8–100 of `A-Za-z0-9_.:-`. Chosen and kept by the caller. */
124
+ idempotencyKey: string;
125
+ /** Who did it, as the App names them (at most 120). */
126
+ actor?: string;
127
+ }
128
+ /** Which debts a payment or write-off is applied to; none = oldest debt first. */
129
+ interface CreditTargets {
130
+ /** `CreditDebt.entryId`s (at most 50). */
131
+ chargeEntryIds?: string[];
132
+ /** Order ids (at most 50). */
133
+ caseIds?: string[];
134
+ }
135
+ export interface CreditPayInput extends CreditWriteBase, CreditTargets {
136
+ /** Whole cents > 0. Refused above what the picked debts owe (`overpayment`). */
137
+ amountCents: number;
138
+ /** A key of the business's payment catalog (`efectivo`, `nequi`…). */
139
+ method: string;
140
+ /** At most 120. */
141
+ reference?: string;
142
+ /** At most 500. */
143
+ note?: string;
144
+ }
145
+ export interface CreditReversePaymentInput extends CreditWriteBase {
146
+ note?: string;
147
+ }
148
+ export interface CreditWriteOffInput extends CreditWriteBase, CreditTargets {
149
+ amountCents: number;
150
+ /** The reason (required, at most 500). */
151
+ note: string;
152
+ }
153
+ export interface CreditOpeningInput extends CreditWriteBase {
154
+ amountCents: number;
155
+ /** `YYYY-MM-DD`. */
156
+ dueOn?: string;
157
+ note?: string;
158
+ }
159
+ export interface CreditPayoutInput extends CreditWriteBase {
160
+ amountCents: number;
161
+ /** The method the money goes out by (catalog key). */
162
+ method: string;
163
+ reference?: string;
164
+ note?: string;
165
+ }
166
+ export declare class CreditAccountsResource {
167
+ private readonly call;
168
+ constructor(call: <T>(method: string, path: string, body?: unknown) => Promise<T>);
169
+ /** `GET /api/v1/credit/accounts` — most owed first, keyset-paged. */
170
+ list(input?: CreditAccountsQuery): Promise<CreditAccountsPage>;
171
+ /** `GET /api/v1/credit/accounts/:contactId` — balance, what is owed per order, credit in favour. 404 `contact_not_found`. */
172
+ get(contactId: string): Promise<CreditAccount>;
173
+ /** `PATCH /api/v1/credit/accounts/:contactId` — block / unblock and set the limit. Returns the account. */
174
+ update(contactId: string, input: UpdateCreditAccountInput): Promise<CreditAccount>;
175
+ /** `GET /api/v1/credit/accounts/:contactId/entries` — the statement, newest first, with the running balance. */
176
+ entries(contactId: string, input?: CreditStatementQuery): Promise<CreditStatement>;
177
+ }
178
+ export declare class CreditResource {
179
+ private readonly client;
180
+ readonly accounts: CreditAccountsResource;
181
+ constructor(client: AgentForgeClient);
182
+ private call;
183
+ /**
184
+ * `POST /api/v1/credit/accounts/:contactId/payments` — an abono. Oldest debt first unless `chargeEntryIds` / `caseIds`
185
+ * pick. The orders it covers become `paid` (`settledBy: 'account'`) in the same transaction. 400 `overpayment`,
186
+ * `nothing_owed`, `invalid_amount`; 409 `idempotency_conflict`. A blocked account still takes abonos (blocked = no new
187
+ * charges). An unknown `method` is a 400 without a code (plain `AgentForgeError`).
188
+ */
189
+ pay(contactId: string, input: CreditPayInput): Promise<CreditWriteResult>;
190
+ /**
191
+ * `POST /api/v1/credit/accounts/:contactId/payments/:entryId/reverse` — an abono typed wrong, undone today. The orders it
192
+ * had covered go back on account. 409 `already_reversed`, `payment_spent`; 400 `wrong_kind`.
193
+ */
194
+ reversePayment(contactId: string, paymentEntryId: string, input: CreditReversePaymentInput): Promise<CreditWriteResult>;
195
+ /**
196
+ * `POST /api/v1/credit/accounts/:contactId/write-offs` — debt given up (`note` = the reason). A written-off order stays
197
+ * `on_account`, never `paid`.
198
+ */
199
+ writeOff(contactId: string, input: CreditWriteOffInput): Promise<CreditWriteResult>;
200
+ /** `POST /api/v1/credit/accounts/:contactId/openings` — debt carried over from the paper notebook. */
201
+ opening(contactId: string, input: CreditOpeningInput): Promise<CreditWriteResult>;
202
+ /** `POST /api/v1/credit/accounts/:contactId/payouts` — credit in the customer's favour handed back (money out). 400 `exceeds_credit`. */
203
+ payout(contactId: string, input: CreditPayoutInput): Promise<CreditWriteResult>;
204
+ }
205
+ export {};
@@ -0,0 +1,165 @@
1
+ "use strict";
2
+ // credit resource (PDK-STORE-CREDIT S3) — the business's customer accounts («fiado»): one append-only ledger per
3
+ // contact. App secret (`sk_`) or tenant-wide `ak_` key; on an installed tenant call it through `af.forTenant(tenantId)`.
4
+ //
5
+ // - `accounts.list / get / update / entries` — who owes what, a statement, block / limit.
6
+ // - `pay` (abono) · `reversePayment` (an abono typed wrong, undone the same day) · `writeOff` (debt given up) ·
7
+ // `opening` (the paper notebook's old debt) · `payout` (credit in the customer's favour handed back).
8
+ // - A charge is NEVER created here: it follows an order (`cases.setOnAccount`), and a revision or cancelling it adjusts
9
+ // or reverses it.
10
+ //
11
+ // The platform does not know WHO may grant, reverse or write off: the host App decides before it calls.
12
+ //
13
+ // Every write needs an `idempotencyKey` (8–100 of `A-Za-z0-9_.:-`) that the CALLER chooses and keeps: the same key with the
14
+ // same request returns the same result with `replayed: true`; with a different request it is refused (`idempotency_conflict`).
15
+ // This SDK never retries a request and never invents a key — on a timeout or a network error, repeat the call with the
16
+ // SAME key. Money is whole cents. Refusals throw `AgentForgeCreditError` (`err.code`, `err.status`).
17
+ //
18
+ // Needs the platform change PDK-STORE-CREDIT S2; an older platform answers 404.
19
+ Object.defineProperty(exports, "__esModule", { value: true });
20
+ exports.CreditResource = exports.CreditAccountsResource = void 0;
21
+ exports.asCreditError = asCreditError;
22
+ const errors_1 = require("../errors");
23
+ const CODES = new Set(errors_1.AGENTFORGE_CREDIT_ERROR_CODES);
24
+ /** A credit-coded failure becomes the typed error; anything else (auth, network, an uncoded 404) is rethrown as is. */
25
+ function asCreditError(err) {
26
+ if (err instanceof errors_1.AgentForgeError && err.code && CODES.has(err.code) && err.status !== 401 && err.status !== 403) {
27
+ let message = err.message;
28
+ if (err.body) {
29
+ try {
30
+ const b = JSON.parse(err.body);
31
+ if (typeof b.message === 'string')
32
+ message = b.message;
33
+ }
34
+ catch {
35
+ /* keep the status message */
36
+ }
37
+ }
38
+ return new errors_1.AgentForgeCreditError(err.status, err.code, message, err.body);
39
+ }
40
+ return err;
41
+ }
42
+ const BASE = '/api/v1/credit';
43
+ const acct = (contactId) => `${BASE}/accounts/${encodeURIComponent(contactId)}`;
44
+ class CreditAccountsResource {
45
+ constructor(call) {
46
+ this.call = call;
47
+ }
48
+ /** `GET /api/v1/credit/accounts` — most owed first, keyset-paged. */
49
+ async list(input = {}) {
50
+ const qs = new URLSearchParams();
51
+ if (input.owing === false)
52
+ qs.set('owing', 'false');
53
+ if (input.overdue)
54
+ qs.set('overdue', 'true');
55
+ if (input.q)
56
+ qs.set('q', input.q);
57
+ if (input.cursor)
58
+ qs.set('cursor', input.cursor);
59
+ if (input.limit !== undefined)
60
+ qs.set('limit', String(input.limit));
61
+ const q = qs.toString();
62
+ return this.call('GET', `${BASE}/accounts${q ? `?${q}` : ''}`);
63
+ }
64
+ /** `GET /api/v1/credit/accounts/:contactId` — balance, what is owed per order, credit in favour. 404 `contact_not_found`. */
65
+ async get(contactId) {
66
+ return this.call('GET', acct(contactId));
67
+ }
68
+ /** `PATCH /api/v1/credit/accounts/:contactId` — block / unblock and set the limit. Returns the account. */
69
+ async update(contactId, input) {
70
+ return this.call('PATCH', acct(contactId), {
71
+ ...(input.status !== undefined ? { status: input.status } : {}),
72
+ ...(input.limitCents !== undefined ? { limitCents: input.limitCents } : {}),
73
+ });
74
+ }
75
+ /** `GET /api/v1/credit/accounts/:contactId/entries` — the statement, newest first, with the running balance. */
76
+ async entries(contactId, input = {}) {
77
+ const qs = new URLSearchParams();
78
+ if (input.limit !== undefined)
79
+ qs.set('limit', String(input.limit));
80
+ if (input.beforeSeq !== undefined)
81
+ qs.set('beforeSeq', String(input.beforeSeq));
82
+ const q = qs.toString();
83
+ return this.call('GET', `${acct(contactId)}/entries${q ? `?${q}` : ''}`);
84
+ }
85
+ }
86
+ exports.CreditAccountsResource = CreditAccountsResource;
87
+ class CreditResource {
88
+ constructor(client) {
89
+ this.client = client;
90
+ this.accounts = new CreditAccountsResource((m, p, b) => this.call(m, p, b));
91
+ }
92
+ async call(method, path, body) {
93
+ try {
94
+ return await this.client.request(method, path, body);
95
+ }
96
+ catch (err) {
97
+ throw asCreditError(err);
98
+ }
99
+ }
100
+ /**
101
+ * `POST /api/v1/credit/accounts/:contactId/payments` — an abono. Oldest debt first unless `chargeEntryIds` / `caseIds`
102
+ * pick. The orders it covers become `paid` (`settledBy: 'account'`) in the same transaction. 400 `overpayment`,
103
+ * `nothing_owed`, `invalid_amount`; 409 `idempotency_conflict`. A blocked account still takes abonos (blocked = no new
104
+ * charges). An unknown `method` is a 400 without a code (plain `AgentForgeError`).
105
+ */
106
+ async pay(contactId, input) {
107
+ return this.call('POST', `${acct(contactId)}/payments`, {
108
+ amountCents: input.amountCents,
109
+ method: input.method,
110
+ idempotencyKey: input.idempotencyKey,
111
+ reference: input.reference,
112
+ note: input.note,
113
+ actor: input.actor,
114
+ chargeEntryIds: input.chargeEntryIds,
115
+ caseIds: input.caseIds,
116
+ });
117
+ }
118
+ /**
119
+ * `POST /api/v1/credit/accounts/:contactId/payments/:entryId/reverse` — an abono typed wrong, undone today. The orders it
120
+ * had covered go back on account. 409 `already_reversed`, `payment_spent`; 400 `wrong_kind`.
121
+ */
122
+ async reversePayment(contactId, paymentEntryId, input) {
123
+ return this.call('POST', `${acct(contactId)}/payments/${encodeURIComponent(paymentEntryId)}/reverse`, {
124
+ idempotencyKey: input.idempotencyKey,
125
+ note: input.note,
126
+ actor: input.actor,
127
+ });
128
+ }
129
+ /**
130
+ * `POST /api/v1/credit/accounts/:contactId/write-offs` — debt given up (`note` = the reason). A written-off order stays
131
+ * `on_account`, never `paid`.
132
+ */
133
+ async writeOff(contactId, input) {
134
+ return this.call('POST', `${acct(contactId)}/write-offs`, {
135
+ amountCents: input.amountCents,
136
+ note: input.note,
137
+ idempotencyKey: input.idempotencyKey,
138
+ actor: input.actor,
139
+ chargeEntryIds: input.chargeEntryIds,
140
+ caseIds: input.caseIds,
141
+ });
142
+ }
143
+ /** `POST /api/v1/credit/accounts/:contactId/openings` — debt carried over from the paper notebook. */
144
+ async opening(contactId, input) {
145
+ return this.call('POST', `${acct(contactId)}/openings`, {
146
+ amountCents: input.amountCents,
147
+ idempotencyKey: input.idempotencyKey,
148
+ dueOn: input.dueOn,
149
+ note: input.note,
150
+ actor: input.actor,
151
+ });
152
+ }
153
+ /** `POST /api/v1/credit/accounts/:contactId/payouts` — credit in the customer's favour handed back (money out). 400 `exceeds_credit`. */
154
+ async payout(contactId, input) {
155
+ return this.call('POST', `${acct(contactId)}/payouts`, {
156
+ amountCents: input.amountCents,
157
+ method: input.method,
158
+ idempotencyKey: input.idempotencyKey,
159
+ reference: input.reference,
160
+ note: input.note,
161
+ actor: input.actor,
162
+ });
163
+ }
164
+ }
165
+ exports.CreditResource = CreditResource;
@@ -18,9 +18,30 @@ export interface NewestMessagesPage {
18
18
  /** Absent on the last page. */
19
19
  nextCursor?: string;
20
20
  }
21
+ /** What a WhatsApp number can carry: image jpeg/png/webp up to 5 MB, document pdf/doc(x)/xls(x)/ppt(x)/txt, video mp4/3gp up to 16 MB. */
22
+ export type InboxAttachmentKind = 'image' | 'document' | 'audio' | 'video';
23
+ /**
24
+ * A file the operator sends. `key` is the `key` that `files.signUpload` returned for a file
25
+ * uploaded in this tenant (`apps/<appId>/tenants/<tenantId>/files/…`): never a URL.
26
+ * Errors: 403 `attachment_not_owned`; 400 `attachment_not_sendable`, `attachment_type_mismatch`,
27
+ * `attachment_caption_too_long`.
28
+ */
29
+ export interface InboxOperatorAttachment {
30
+ key: string;
31
+ kind: InboxAttachmentKind;
32
+ /** Must match the file that was uploaded. */
33
+ mimeType: string;
34
+ fileName?: string;
35
+ /** ≤ 1024 characters. Give it here OR as `text`, never both. */
36
+ caption?: string;
37
+ /** Checked against the channel's cap when sent. */
38
+ sizeBytes?: number;
39
+ }
21
40
  export interface SendMessageInput {
22
- /** The operator's text. */
23
- text: string;
41
+ /** The operator's text. Optional when `attachment` is given (then use `attachment.caption`). */
42
+ text?: string;
43
+ /** One file. `text` and `attachment.caption` together are refused. */
44
+ attachment?: InboxOperatorAttachment;
24
45
  /** Default true. Toggle off when the operator wants to chime in
25
46
  * without taking the thread away from the agent. */
26
47
  pauseAgent?: boolean;
package/dist/types.d.ts CHANGED
@@ -525,6 +525,9 @@ export interface ToolCallbackPayload {
525
525
  tenantId: string;
526
526
  agentId: string;
527
527
  conversationId: string;
528
+ /** The inbox thread of the turn, when the tool ran on an inbox turn.
529
+ * Absent otherwise (and on an older platform). */
530
+ threadId?: string;
528
531
  /** The App's end user of that turn, when the tool ran on the App-user
529
532
  * chat path (`chat.streamMessageForAppUser`). Absent otherwise. */
530
533
  externalUserId?: string;
@@ -2540,7 +2543,9 @@ export interface CaseView {
2540
2543
  * reported it) → `paid` | `rejected`; then `refunded`, `partially_refunded`,
2541
2544
  * `reversed`; `voided` when the order ended unpaid. Completing never marks it paid.
2542
2545
  */
2543
- export type CasePaymentStatus = 'unpaid' | 'awaiting_payment' | 'pending_confirmation' | 'paid' | 'rejected' | 'refunded' | 'partially_refunded' | 'reversed' | 'voided';
2546
+ export type CasePaymentStatus = 'unpaid' | 'awaiting_payment' | 'pending_confirmation' | 'paid' | 'rejected' | 'refunded' | 'partially_refunded' | 'reversed' | 'voided'
2547
+ /** PDK-STORE-CREDIT — «Fiado»: left on the customer's account (`cases.setOnAccount`). Neither to collect nor payable by chat. Absent on an older platform. */
2548
+ | 'on_account';
2544
2549
  /** The account the customer chose, as it was then (a later edit never rewrites a sale). */
2545
2550
  export interface CasePaymentAccount {
2546
2551
  id: string;
@@ -2586,12 +2591,18 @@ export interface CasePayment {
2586
2591
  chosenAt?: 'checkout' | 'chat' | 'receipt';
2587
2592
  /** The order ended undone after the customer reported (or the business confirmed) the payment: check it and refund. */
2588
2593
  refundDue?: boolean;
2594
+ /**
2595
+ * PDK-STORE-CREDIT — `paid` because the customer account's abonos covered the order's fiado (money counted abono by
2596
+ * abono, never on the order). Absent otherwise and on an older platform; cleared when it goes back on account.
2597
+ */
2598
+ settledBy?: 'account';
2589
2599
  history: Array<{
2590
2600
  status: CasePaymentStatus;
2591
2601
  by: 'assistant' | 'customer' | 'business' | 'system';
2592
2602
  at: string;
2593
2603
  note?: string;
2594
2604
  amountCents?: number;
2605
+ settledBy?: 'account';
2595
2606
  }>;
2596
2607
  }
2597
2608
  /** The payment as a receipt's public link shows it (no proof image, only that one was sent). */
@@ -3007,6 +3018,47 @@ export interface CaseClosingMethod {
3007
3018
  collectedCents: number;
3008
3019
  refundedCents: number;
3009
3020
  netCents: number;
3021
+ /** PDK-STORE-CREDIT — the net of ORDER payments by this method. `fromSalesCents + fromAccountCents = netCents`. Absent on an older platform. */
3022
+ fromSalesCents?: number;
3023
+ /** PDK-STORE-CREDIT — the net of the customer ACCOUNTS' movements by this method: abonos − reversals − payouts. */
3024
+ fromAccountCents?: number;
3025
+ /** PDK-STORE-CREDIT — abonos received by this method (inside `collectedCents`). */
3026
+ accountReceivedCents?: number;
3027
+ /** PDK-STORE-CREDIT — abonos reversed + payouts by this method (inside `refundedCents`). */
3028
+ accountOutCents?: number;
3029
+ }
3030
+ /**
3031
+ * PDK-STORE-CREDIT — the customer accounts' part of a closing (always present on a platform that has them; all zeros for
3032
+ * a business that never used fiado). closing = opening + charged + prior debt + adjustments − abonos(net) − write-offs + payouts.
3033
+ */
3034
+ export interface CaseClosingReceivables {
3035
+ openingCents: number;
3036
+ /** Fiado of the range: orders left on account (their whole total). */
3037
+ chargedCents: number;
3038
+ /** The paper notebook's old debt entered in the range. */
3039
+ priorDebtCents: number;
3040
+ /** Revised receipts (±) and cancelled orders (−) of orders on account. */
3041
+ adjustmentsCents: number;
3042
+ paymentsByMethod: Array<{
3043
+ method: string;
3044
+ methodName: string;
3045
+ receivedCents: number;
3046
+ reversedCents: number;
3047
+ netCents: number;
3048
+ }>;
3049
+ paymentsNetCents: number;
3050
+ writeOffCents: number;
3051
+ /** Credit in the customer's favour handed back (money out). */
3052
+ payoutCents: number;
3053
+ payoutsByMethod: Array<{
3054
+ method: string;
3055
+ methodName: string;
3056
+ cents: number;
3057
+ }>;
3058
+ closingCents: number;
3059
+ /** Customers who owe something at the end of the range. */
3060
+ customers: number;
3061
+ balanced: boolean;
3010
3062
  }
3011
3063
  /** AGF-CASH-REGISTER — one order sent in a closing's range. */
3012
3064
  export interface CaseClosingOrder {
@@ -3075,7 +3127,18 @@ export interface CaseClosingReport {
3075
3127
  netCents: number;
3076
3128
  /** Payments confirmed whose order has no known total: in no sum. */
3077
3129
  unpricedPayments: number;
3130
+ /** PDK-STORE-CREDIT — Σ `fromSalesCents` over the methods (what the orders' payments brought in, net). Absent on an older platform. */
3131
+ fromSalesCents?: number;
3132
+ /** PDK-STORE-CREDIT — Σ `fromAccountCents` (the customer accounts' abonos, net of reversals and payouts). */
3133
+ fromAccountCents?: number;
3078
3134
  };
3135
+ /** PDK-STORE-CREDIT — customer accounts (fiado). Absent on an older platform. */
3136
+ receivables?: CaseClosingReceivables;
3137
+ /**
3138
+ * PDK-STORE-CREDIT — set only when `clampToClock` cut the range short: the `to` the caller asked for, which was ahead of the
3139
+ * platform's clock. `to` is then the clamped instant — the next closing must start from `to`, never from this.
3140
+ */
3141
+ requestedTo?: string;
3079
3142
  /** The cash the register should have received, for the count. */
3080
3143
  cash: {
3081
3144
  collectedCents: number;
@@ -3102,6 +3165,50 @@ export interface CaseClosingReport {
3102
3165
  orders: CaseClosingOrder[];
3103
3166
  ordersTruncated: boolean;
3104
3167
  }
3168
+ /**
3169
+ * PDK-STORE-CREDIT — `cases.setOnAccount`: «Dejar como fiado». The status and the ledger charge are one transaction.
3170
+ * `idempotencyKey` (8–64 of `A-Za-z0-9_.:-`) is required: a retried key returns the same result with `replayed: true`.
3171
+ */
3172
+ export interface SetOnAccountInput {
3173
+ idempotencyKey: string;
3174
+ /** Only when the case has no contact yet (a contact with a name and a phone). */
3175
+ contactId?: string;
3176
+ /** `YYYY-MM-DD`. */
3177
+ dueOn?: string;
3178
+ /** At most 500 characters. */
3179
+ note?: string;
3180
+ /** Leave it as fiado past the account's limit. The HOST decides who may; the platform does not know. */
3181
+ overrideLimit?: boolean;
3182
+ /** The App's default limit (cents) for an account with none of its own; checked with the down payment taken off. */
3183
+ defaultLimitCents?: number;
3184
+ /** Cash or transfer received now, by one of the business's payment accounts (an `accountId` of `directForm().payment.options`). */
3185
+ downPayment?: {
3186
+ amountCents: number;
3187
+ accountId: string;
3188
+ reference?: string;
3189
+ };
3190
+ /** Who did it, as the App names them (at most 120). */
3191
+ actor?: string;
3192
+ }
3193
+ /** `cases.setOnAccount` answers the case as `cases.get` does, plus whether the key had been used before. */
3194
+ export type SetOnAccountResult = CaseView & {
3195
+ replayed: boolean;
3196
+ };
3197
+ /** PDK-STORE-CREDIT — `cases.account(caseId)`: what ONE order owes on the customer account (never the account). */
3198
+ export interface CaseAccount {
3199
+ onAccount: boolean;
3200
+ /** 0 when not on account. */
3201
+ totalCents?: number;
3202
+ collectedCents?: number;
3203
+ writtenOffCents?: number;
3204
+ outstandingCents?: number;
3205
+ payments: Array<{
3206
+ entryId: string;
3207
+ method: string | null;
3208
+ cents: number;
3209
+ occurredAt: string;
3210
+ }>;
3211
+ }
3105
3212
  export interface ListCasesInput {
3106
3213
  state?: CaseState[];
3107
3214
  type?: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentforge-io/sdk-server",
3
- "version": "4.81.0",
3
+ "version": "4.83.0",
4
4
  "description": "Server-side SDK for backend apps integrating with AgentForge platform. Auth via ChatToken, ak_live_ API key or App secret (sk_live_), with App installations across tenants.",
5
5
  "license": "MIT",
6
6
  "main": "dist/index.js",