i18n - docs translations (#18528)

Created by Github action

---------

Co-authored-by: github-actions <github-actions@twenty.com>
Co-authored-by: Charles Bochet <charles@twenty.com>
This commit is contained in:
github-actions[bot]
2026-03-10 14:15:51 +01:00
committed by GitHub
parent c73a660e46
commit 59e9563fc7
17 changed files with 750 additions and 215 deletions
@@ -171,7 +171,7 @@ export default defineObject({
ستضيف الأوامر اللاحقة مزيدًا من الملفات والمجلدات:
* سيقوم `yarn twenty app:dev` بتوليد عميلين API مضبوطي الأنواع تلقائيًا في `node_modules/twenty-sdk/generated`: `CoreApiClient` (لبيانات مساحة العمل عبر `/graphql`) و`MetadataApiClient` (لتكوين مساحة العمل وتحميل الملفات عبر `/metadata`).
* سيقوم `yarn twenty app:dev` بتوليد عميلين API مضبوطي الأنواع تلقائيًا في `node_modules/twenty-sdk/clients`: `CoreApiClient` (لبيانات مساحة العمل عبر `/graphql`) و`MetadataApiClient` (لتكوين مساحة العمل وتحميل الملفات عبر `/metadata`).
* `yarn twenty entity:add` سيضيف ملفات تعريف الكيانات ضمن `src/` لكائناتك المخصّصة، والوظائف، ومكوّنات الواجهة الأمامية، والأدوار، والمهارات، وغير ذلك.
## المصادقة
@@ -228,7 +228,7 @@ yarn twenty auth:status
| `defineView()` | تعريف العروض المحفوظة للكائنات |
| `defineNavigationMenuItem()` | تعريف روابط التنقل في الشريط الجانبي |
| `defineSkill()` | عرّف مهارات وكيل الذكاء الاصطناعي |
| `defineAgent()` | Define AI agents with system prompts |
| `defineAgent()` | عرِّف وكلاء الذكاء الاصطناعي باستخدام موجهات النظام |
تتحقق هذه الدوال من تكوينك وقت البناء وتوفّر إكمالًا تلقائيًا في بيئة التطوير وأمان الأنواع.
@@ -321,6 +321,72 @@ export default defineObject({
لكن هذا غير مستحسن.
</Note>
### Defining fields on existing objects
Use `defineField()` to add custom fields to existing objects — both standard objects (like `company`, `person`, `opportunity`) and custom objects defined by other apps. Each field lives in its own file and references the target object by its `universalIdentifier`.
To reference standard objects, import `STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS` from `twenty-sdk`. This constant provides stable identifiers for all built-in objects and their fields:
```typescript
// src/fields/apollo-total-funding.field.ts
import {
defineField,
FieldType,
STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS,
} from 'twenty-sdk';
export default defineField({
universalIdentifier: 'c90ae72d-4ddf-4f22-882f-eef98c91e40e',
objectUniversalIdentifier:
STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.company.universalIdentifier,
type: FieldType.CURRENCY,
name: 'apolloTotalFunding',
label: 'Total Funding',
description: 'Total funding raised by the company',
icon: 'IconCash',
});
```
النقاط الرئيسية:
* `objectUniversalIdentifier` tells Twenty which object to attach the field to. Use `STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.<objectName>.universalIdentifier` for standard objects.
* Each field requires its own stable `universalIdentifier`, a `name`, `type`, `label`, and the target `objectUniversalIdentifier`.
* You can scaffold new fields using `yarn twenty entity:add` and choosing the field option.
* `STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS` is also exported as `STANDARD_OBJECT` for convenience — both refer to the same constant.
Available standard objects include: `attachment`, `blocklist`, `calendarChannel`, `calendarEvent`, `calendarEventParticipant`, `company`, `connectedAccount`, `dashboard`, `favorite`, `favoriteFolder`, `message`, `messageChannel`, `messageParticipant`, `messageThread`, `note`, `noteTarget`, `opportunity`, `person`, `task`, `taskTarget`, `timelineActivity`, `workflow`, `workflowAutomatedTrigger`, `workflowRun`, `workflowVersion`, and `workspaceMember`.
Each standard object also exposes its field identifiers. For example, to reference a specific field on a standard object in role permissions:
```typescript
STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.company.fields.name.universalIdentifier
```
#### Relation fields on existing objects
You can also define relation fields that link existing objects to your custom objects:
```typescript
// src/fields/people-on-call-recording.field.ts
import { defineField, FieldType, RelationType, STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS } from 'twenty-sdk';
import { CALL_RECORDING_OBJECT_UNIVERSAL_IDENTIFIER } from 'src/objects/call-recording';
import { CALL_RECORDING_ON_PERSON_ID } from 'src/fields/call-recording-on-person.field';
export default defineField({
universalIdentifier: '4a2b3c4d-5e6f-7a8b-9c0d-1e2f3a4b5c6d',
objectUniversalIdentifier:
CALL_RECORDING_OBJECT_UNIVERSAL_IDENTIFIER,
type: FieldType.RELATION,
name: 'person',
label: 'Person',
relationTargetObjectMetadataUniversalIdentifier:
STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.person.universalIdentifier,
relationTargetFieldMetadataUniversalIdentifier:
CALL_RECORDING_ON_PERSON_ID,
relationType: RelationType.MANY_TO_ONE,
});
```
### تكوين التطبيق (application-config.ts)
كل تطبيق لديه ملف واحد `application-config.ts` يصف:
@@ -434,7 +500,7 @@ export default defineRole({
// src/app/createPostCard.logic-function.ts
import { defineLogicFunction } from 'twenty-sdk';
import type { DatabaseEventPayload, ObjectRecordCreateEvent, CronPayload, RoutePayload } from 'twenty-sdk';
import { CoreApiClient, type Person } from 'twenty-sdk/generated';
import { CoreApiClient, type Person } from 'twenty-sdk/clients';
const handler = async (params: RoutePayload) => {
const client = new CoreApiClient();
@@ -679,7 +745,7 @@ const handler = async (event: RoutePayload) => {
```typescript
// src/logic-functions/enrich-company.logic-function.ts
import { defineLogicFunction } from 'twenty-sdk';
import { CoreApiClient } from 'twenty-sdk/generated';
import { CoreApiClient } from 'twenty-sdk/clients';
const handler = async (params: { companyName: string; domain?: string }) => {
const client = new CoreApiClient();
@@ -806,9 +872,9 @@ export default defineSkill({
* **مُنشأ بالقالب**: شغِّل `yarn twenty entity:add` واختر خيار إضافة مهارة جديدة.
* **يدوي**: أنشئ ملفًا جديدًا واستخدم `defineSkill()` مع اتباع النمط نفسه.
### Agents
### الوكلاء
Agents define AI agents with system prompts that can operate within your workspace. Use `defineAgent()` to define agents with built-in validation:
تمكّنك ميزة الوكلاء من تعريف وكلاء ذكاء اصطناعي قادرين على العمل ضمن مساحة عملك، باستخدام موجهات النظام. استخدم `defineAgent()` لتعريف وكلاء مع تحقق مدمج:
```typescript
// src/agents/example-agent.ts
@@ -830,26 +896,27 @@ export default defineAgent({
النقاط الرئيسية:
* `name` is a unique identifier string for the agent (kebab-case recommended).
* `name` هي سلسلة معرّف فريدة للوكيل (يُنصَح باستخدام kebab-case).
* `label` هو اسم العرض المقروء للبشر الظاهر في واجهة المستخدم.
* `prompt` contains the system prompt — this is the instruction text that defines the agent's behavior.
* `prompt` يحتوي موجه النظام — وهو نص التعليمات الذي يحدد سلوك الوكيل.
* `icon` (اختياري) يحدّد الأيقونة المعروضة في واجهة المستخدم.
* `description` (optional) provides additional context about the agent's purpose.
* `description` (اختياري) يوفّر سياقًا إضافيًا حول غرض الوكيل.
You can create new agents in two ways:
يمكنك إنشاء وكلاء جدد بطريقتين:
* **Scaffolded**: Run `yarn twenty entity:add` and choose the option to add a new agent.
* **Manual**: Create a new file and use `defineAgent()`, following the same pattern.
* **مُنشأ بالقالب**: شغِّل `yarn twenty entity:add` واختر خيار إضافة وكيل جديد.
* **يدوي**: أنشئ ملفًا جديدًا واستخدم `defineAgent()` مع اتباع النمط نفسه.
### عملاء مُولَّدون مضبوطو الأنواع
يتم توليد عميلين مضبوطي الأنواع تلقائيًا بواسطة `yarn twenty app:dev` وتخزينهما في `node_modules/twenty-sdk/generated` استنادًا إلى مخطط مساحة العمل لديك:
يتم توليد عميلين مضبوطي الأنواع تلقائيًا بواسطة `yarn twenty app:dev` وتخزينهما في `node_modules/twenty-sdk/clients` استنادًا إلى مخطط مساحة العمل لديك:
* **`CoreApiClient`** — يُجري استعلامات إلى نقطة النهاية `/graphql` للحصول على بيانات مساحة العمل
* **`MetadataApiClient`** — يستعلم عن نقطة النهاية `/metadata` لتكوين مساحة العمل وتحميل الملفات.
```typescript
import { CoreApiClient, MetadataApiClient } from 'twenty-sdk/generated';
import { CoreApiClient } from 'twenty-sdk/clients';
import { MetadataApiClient } from 'twenty-sdk/clients';
const client = new CoreApiClient();
const { me } = await client.query({ me: { id: true, displayName: true } });
@@ -858,7 +925,7 @@ const metadataClient = new MetadataApiClient();
const { currentWorkspace } = await metadataClient.query({ currentWorkspace: { id: true } });
```
يُعاد توليد كلا العميلين تلقائيًا بواسطة `yarn twenty app:dev` كلما تغيّرت كائناتك أو حقولك.
`CoreApiClient` يُعاد توليده تلقائيًا بواسطة `yarn twenty app:dev` كلما تغيّرت كائناتك أو حقولك. `MetadataApiClient` يأتي مُجهزًا مسبقًا مع SDK.
#### بيانات الاعتماد وقت التشغيل في الوظائف المنطقية
@@ -875,10 +942,10 @@ const { currentWorkspace } = await metadataClient.query({ currentWorkspace: { id
#### رفع الملفات
يتضمن `MetadataApiClient` المُولَّد طريقة `uploadFile` لإرفاق الملفات بالحقول من نوع ملف ضمن كائنات مساحة العمل الخاصة بك. نظرًا لأن عملاء GraphQL القياسيون لا يدعمون تحميل الملفات متعددة الأجزاء افتراضيًا، يوفر العميل هذه الطريقة المخصصة التي تطبق [مواصفة طلب GraphQL متعدد الأجزاء](https://github.com/jaydenseric/graphql-multipart-request-spec) في الخلفية.
يتضمن `MetadataApiClient` طريقة `uploadFile` لإرفاق الملفات بالحقول من نوع ملف ضمن كائنات مساحة العمل الخاصة بك. نظرًا لأن عملاء GraphQL القياسيون لا يدعمون تحميل الملفات متعددة الأجزاء افتراضيًا، يوفر العميل هذه الطريقة المخصصة التي تطبق [مواصفة طلب GraphQL متعدد الأجزاء](https://github.com/jaydenseric/graphql-multipart-request-spec) في الخلفية.
```typescript
import { MetadataApiClient } from 'twenty-sdk/generated';
import { MetadataApiClient } from 'twenty-sdk/clients';
import * as fs from 'fs';
const metadataClient = new MetadataApiClient();
+2 -2
View File
@@ -149,8 +149,8 @@
"extend": {
"label": "التوسيع",
"groups": {
"extendCapabilities": {
"label": "القدرات"
"apps": {
"label": "التطبيقات"
}
}
},
@@ -171,7 +171,7 @@ export default defineObject({
Pozdější příkazy přidají další soubory a složky:
* `yarn twenty app:dev` automaticky vygeneruje dva typované API klienty v `node_modules/twenty-sdk/generated`: `CoreApiClient` (pro data pracovního prostoru přes `/graphql`) a `MetadataApiClient` (pro konfiguraci pracovního prostoru a nahrávání souborů přes `/metadata`).
* `yarn twenty app:dev` will auto-generate two typed API clients in `node_modules/twenty-sdk/clients`: `CoreApiClient` (for workspace data via `/graphql`) and `MetadataApiClient` (for workspace configuration and file uploads via `/metadata`).
* `yarn twenty entity:add` přidá soubory s definicemi entit do `src/` pro vaše vlastní objekty, funkce, frontové komponenty, role, dovednosti a další.
## Ověření
@@ -228,7 +228,7 @@ SDK poskytuje pomocné funkce pro definování entit vaší aplikace. Jak je pop
| `defineView()` | Definujte uložená zobrazení pro objekty |
| `defineNavigationMenuItem()` | Definujte odkazy postranní navigace |
| `defineSkill()` | Definuje dovednosti agenta AI |
| `defineAgent()` | Define AI agents with system prompts |
| `defineAgent()` | Definujte AI agenty pomocí systémových promptů |
Tyto funkce validují vaši konfiguraci v době sestavení a poskytují automatické doplňování v IDE a typovou bezpečnost.
@@ -434,7 +434,7 @@ Každý soubor funkce používá `defineLogicFunction()` k exportu konfigurace s
// src/app/createPostCard.logic-function.ts
import { defineLogicFunction } from 'twenty-sdk';
import type { DatabaseEventPayload, ObjectRecordCreateEvent, CronPayload, RoutePayload } from 'twenty-sdk';
import { CoreApiClient, type Person } from 'twenty-sdk/generated';
import { CoreApiClient, type Person } from 'twenty-sdk/clients';
const handler = async (params: RoutePayload) => {
const client = new CoreApiClient();
@@ -679,7 +679,7 @@ Chcete-li označit logickou funkci jako nástroj, nastavte `isTool: true` a posk
```typescript
// src/logic-functions/enrich-company.logic-function.ts
import { defineLogicFunction } from 'twenty-sdk';
import { CoreApiClient } from 'twenty-sdk/generated';
import { CoreApiClient } from 'twenty-sdk/clients';
const handler = async (params: { companyName: string; domain?: string }) => {
const client = new CoreApiClient();
@@ -808,7 +808,7 @@ Nové dovednosti můžete vytvářet dvěma způsoby:
### Agenti
Agents define AI agents with system prompts that can operate within your workspace. Use `defineAgent()` to define agents with built-in validation:
Agenti jsou AI agenti se systémovými prompty, kteří mohou fungovat ve vašem pracovním prostoru. K definování agentů s vestavěnou validací použijte `defineAgent()`:
```typescript
// src/agents/example-agent.ts
@@ -830,26 +830,27 @@ export default defineAgent({
Hlavní body:
* `name` is a unique identifier string for the agent (kebab-case recommended).
* `name` je jedinečný identifikátor agenta (doporučuje se kebab-case).
* `label` je uživatelsky čitelný název zobrazovaný v UI.
* `prompt` contains the system prompt — this is the instruction text that defines the agent's behavior.
* `prompt` obsahuje systémový prompt — jde o instrukční text, který určuje chování agenta.
* `icon` (volitelné) nastavuje ikonu zobrazovanou v UI.
* `description` (optional) provides additional context about the agent's purpose.
* `description` (volitelné) poskytuje doplňující kontext o účelu agenta.
You can create new agents in two ways:
Nové agenty můžete vytvářet dvěma způsoby:
* **Scaffolded**: Run `yarn twenty entity:add` and choose the option to add a new agent.
* **Manual**: Create a new file and use `defineAgent()`, following the same pattern.
* **Vygenerované**: Spusťte `yarn twenty entity:add` a zvolte možnost přidat nového agenta.
* **Ruční**: Vytvořte nový soubor a použijte `defineAgent()` podle stejného vzoru.
### Generované typované klienty
Dva typované klienty jsou automaticky generovány pomocí `yarn twenty app:dev` a ukládají se do `node_modules/twenty-sdk/generated` podle schématu vašeho pracovního prostoru:
Two typed clients are auto-generated by `yarn twenty app:dev` and stored in `node_modules/twenty-sdk/clients` based on your workspace schema:
* **`CoreApiClient`** — provádí dotazy na endpoint `/graphql` za účelem získání dat pracovního prostoru
* **`MetadataApiClient`** — odesílá dotazy na endpoint `/metadata` pro konfiguraci pracovního prostoru a nahrávání souborů
```typescript
import { CoreApiClient, MetadataApiClient } from 'twenty-sdk/generated';
import { CoreApiClient } from 'twenty-sdk/clients';
import { MetadataApiClient } from 'twenty-sdk/clients';
const client = new CoreApiClient();
const { me } = await client.query({ me: { id: true, displayName: true } });
@@ -858,7 +859,7 @@ const metadataClient = new MetadataApiClient();
const { currentWorkspace } = await metadataClient.query({ currentWorkspace: { id: true } });
```
Oba klienti se automaticky znovu generují pomocí `yarn twenty app:dev` kdykoli se změní vaše objekty nebo pole.
`CoreApiClient` is re-generated automatically by `yarn twenty app:dev` whenever your objects or fields change. `MetadataApiClient` ships pre-built with the SDK.
#### Běhové přihlašovací údaje v logických funkcích
@@ -875,10 +876,10 @@ Poznámky:
#### Nahrávání souborů
Vygenerovaný `MetadataApiClient` obsahuje metodu `uploadFile` pro připojování souborů k polím typu souboru u objektů ve vašem pracovním prostoru. Protože standardní klienti GraphQL nativně nepodporují nahrávání souborů pomocí multipart, klient poskytuje tuto speciální metodu, která interně implementuje [specifikaci multipart požadavků GraphQL](https://github.com/jaydenseric/graphql-multipart-request-spec).
The `MetadataApiClient` includes an `uploadFile` method for attaching files to file-type fields on your workspace objects. Protože standardní klienti GraphQL nativně nepodporují nahrávání souborů pomocí multipart, klient poskytuje tuto speciální metodu, která interně implementuje [specifikaci multipart požadavků GraphQL](https://github.com/jaydenseric/graphql-multipart-request-spec).
```typescript
import { MetadataApiClient } from 'twenty-sdk/generated';
import { MetadataApiClient } from 'twenty-sdk/clients';
import * as fs from 'fs';
const metadataClient = new MetadataApiClient();
@@ -171,7 +171,7 @@ export default defineObject({
Spätere Befehle fügen weitere Dateien und Ordner hinzu:
* `yarn twenty app:dev` generiert automatisch zwei typisierte API-Clients in `node_modules/twenty-sdk/generated`: `CoreApiClient` (für Arbeitsbereichsdaten über `/graphql`) und `MetadataApiClient` (für Arbeitsbereichskonfiguration und Datei-Uploads über `/metadata`).
* `yarn twenty app:dev` generiert automatisch zwei typisierte API-Clients in `node_modules/twenty-sdk/clients`: `CoreApiClient` (für Arbeitsbereichsdaten über `/graphql`) und `MetadataApiClient` (für Arbeitsbereichskonfiguration und Datei-Uploads über `/metadata`).
* `yarn twenty entity:add` fügt unter `src/` Entitätsdefinitionsdateien für Ihre benutzerdefinierten Objekte, Funktionen, Frontend-Komponenten, Rollen, Skills und mehr hinzu.
## Authentifizierung
@@ -228,7 +228,7 @@ Das SDK stellt Hilfsfunktionen bereit, um die Entitäten Ihrer App zu definieren
| `defineView()` | Gespeicherte Views für Objekte definieren |
| `defineNavigationMenuItem()` | Seitenleisten-Navigationslinks definieren |
| `defineSkill()` | Definieren Sie Skills für KI-Agenten |
| `defineAgent()` | Define AI agents with system prompts |
| `defineAgent()` | Definieren Sie KI-Agenten mit System-Prompts |
Diese Funktionen validieren Ihre Konfiguration zur Build-Zeit und bieten IDE-Autovervollständigung sowie Typsicherheit.
@@ -321,6 +321,72 @@ Sie können Standardfelder überschreiben, indem Sie in Ihrem `fields`-Array ein
dies wird jedoch nicht empfohlen.
</Note>
### Defining fields on existing objects
Use `defineField()` to add custom fields to existing objects — both standard objects (like `company`, `person`, `opportunity`) and custom objects defined by other apps. Each field lives in its own file and references the target object by its `universalIdentifier`.
To reference standard objects, import `STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS` from `twenty-sdk`. This constant provides stable identifiers for all built-in objects and their fields:
```typescript
// src/fields/apollo-total-funding.field.ts
import {
defineField,
FieldType,
STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS,
} from 'twenty-sdk';
export default defineField({
universalIdentifier: 'c90ae72d-4ddf-4f22-882f-eef98c91e40e',
objectUniversalIdentifier:
STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.company.universalIdentifier,
type: FieldType.CURRENCY,
name: 'apolloTotalFunding',
label: 'Total Funding',
description: 'Total funding raised by the company',
icon: 'IconCash',
});
```
Hauptpunkte:
* `objectUniversalIdentifier` tells Twenty which object to attach the field to. Use `STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.<objectName>.universalIdentifier` for standard objects.
* Each field requires its own stable `universalIdentifier`, a `name`, `type`, `label`, and the target `objectUniversalIdentifier`.
* You can scaffold new fields using `yarn twenty entity:add` and choosing the field option.
* `STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS` is also exported as `STANDARD_OBJECT` for convenience — both refer to the same constant.
Available standard objects include: `attachment`, `blocklist`, `calendarChannel`, `calendarEvent`, `calendarEventParticipant`, `company`, `connectedAccount`, `dashboard`, `favorite`, `favoriteFolder`, `message`, `messageChannel`, `messageParticipant`, `messageThread`, `note`, `noteTarget`, `opportunity`, `person`, `task`, `taskTarget`, `timelineActivity`, `workflow`, `workflowAutomatedTrigger`, `workflowRun`, `workflowVersion`, and `workspaceMember`.
Each standard object also exposes its field identifiers. For example, to reference a specific field on a standard object in role permissions:
```typescript
STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.company.fields.name.universalIdentifier
```
#### Relation fields on existing objects
You can also define relation fields that link existing objects to your custom objects:
```typescript
// src/fields/people-on-call-recording.field.ts
import { defineField, FieldType, RelationType, STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS } from 'twenty-sdk';
import { CALL_RECORDING_OBJECT_UNIVERSAL_IDENTIFIER } from 'src/objects/call-recording';
import { CALL_RECORDING_ON_PERSON_ID } from 'src/fields/call-recording-on-person.field';
export default defineField({
universalIdentifier: '4a2b3c4d-5e6f-7a8b-9c0d-1e2f3a4b5c6d',
objectUniversalIdentifier:
CALL_RECORDING_OBJECT_UNIVERSAL_IDENTIFIER,
type: FieldType.RELATION,
name: 'person',
label: 'Person',
relationTargetObjectMetadataUniversalIdentifier:
STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.person.universalIdentifier,
relationTargetFieldMetadataUniversalIdentifier:
CALL_RECORDING_ON_PERSON_ID,
relationType: RelationType.MANY_TO_ONE,
});
```
### Anwendungskonfiguration (application-config.ts)
Jede App hat eine einzelne Datei `application-config.ts`, die Folgendes beschreibt:
@@ -434,7 +500,7 @@ Jede Funktionsdatei verwendet `defineLogicFunction()`, um eine Konfiguration mit
// src/app/createPostCard.logic-function.ts
import { defineLogicFunction } from 'twenty-sdk';
import type { DatabaseEventPayload, ObjectRecordCreateEvent, CronPayload, RoutePayload } from 'twenty-sdk';
import { CoreApiClient, type Person } from 'twenty-sdk/generated';
import { CoreApiClient, type Person } from 'twenty-sdk/clients';
const handler = async (params: RoutePayload) => {
const client = new CoreApiClient();
@@ -679,7 +745,7 @@ Um eine Logikfunktion als Tool zu markieren, setzen Sie `isTool: true` und geben
```typescript
// src/logic-functions/enrich-company.logic-function.ts
import { defineLogicFunction } from 'twenty-sdk';
import { CoreApiClient } from 'twenty-sdk/generated';
import { CoreApiClient } from 'twenty-sdk/clients';
const handler = async (params: { companyName: string; domain?: string }) => {
const client = new CoreApiClient();
@@ -808,7 +874,7 @@ Sie können neue Skills auf zwei Arten erstellen:
### Agenten
Agents define AI agents with system prompts that can operate within your workspace. Use `defineAgent()` to define agents with built-in validation:
Mit Agents definieren Sie KI-Agenten mit System-Prompts, die in Ihrem Arbeitsbereich arbeiten können. Verwenden Sie `defineAgent()`, um Agenten mit eingebauter Validierung zu definieren:
```typescript
// src/agents/example-agent.ts
@@ -830,26 +896,27 @@ export default defineAgent({
Hauptpunkte:
* `name` is a unique identifier string for the agent (kebab-case recommended).
* `name` ist eine eindeutige Kennung (als Zeichenfolge) für den Agenten (kebab-case empfohlen).
* `label` ist der menschenlesbare Anzeigename, der in der UI angezeigt wird.
* `prompt` contains the system prompt — this is the instruction text that defines the agent's behavior.
* `prompt` enthält den System-Prompt — dies ist der Anweisungstext, der das Verhalten des Agenten definiert.
* `icon` (optional) legt das in der UI angezeigte Symbol fest.
* `description` (optional) provides additional context about the agent's purpose.
* `description` (optional) liefert zusätzlichen Kontext zum Zweck des Agenten.
You can create new agents in two ways:
Sie können neue Agenten auf zwei Arten erstellen:
* **Scaffolded**: Run `yarn twenty entity:add` and choose the option to add a new agent.
* **Manual**: Create a new file and use `defineAgent()`, following the same pattern.
* **Generiert**: Führen Sie `yarn twenty entity:add` aus und wählen Sie die Option zum Hinzufügen eines neuen Agenten.
* **Manuell**: Erstellen Sie eine neue Datei und verwenden Sie `defineAgent()` nach demselben Muster.
### Generierte typisierte Clients
Zwei typisierte Clients werden von `yarn twenty app:dev` automatisch generiert und basierend auf Ihrem Arbeitsbereichs-Schema in `node_modules/twenty-sdk/generated` gespeichert:
Zwei typisierte Clients werden von `yarn twenty app:dev` automatisch generiert und basierend auf Ihrem Arbeitsbereichs-Schema in `node_modules/twenty-sdk/clients` gespeichert:
* **`CoreApiClient`** — fragt den `/graphql`-Endpunkt nach Arbeitsbereichsdaten ab
* **`MetadataApiClient`** — ruft über den Endpunkt `/metadata` die Arbeitsbereichskonfiguration und Datei-Uploads ab.
```typescript
import { CoreApiClient, MetadataApiClient } from 'twenty-sdk/generated';
import { CoreApiClient } from 'twenty-sdk/clients';
import { MetadataApiClient } from 'twenty-sdk/clients';
const client = new CoreApiClient();
const { me } = await client.query({ me: { id: true, displayName: true } });
@@ -858,7 +925,7 @@ const metadataClient = new MetadataApiClient();
const { currentWorkspace } = await metadataClient.query({ currentWorkspace: { id: true } });
```
Beide Clients werden von `yarn twenty app:dev` automatisch neu generiert, sobald sich Ihre Objekte oder Felder ändern.
`CoreApiClient` wird von `yarn twenty app:dev` automatisch neu generiert, sobald sich Ihre Objekte oder Felder ändern. `MetadataApiClient` ist im SDK bereits enthalten.
#### Laufzeit-Anmeldedaten in Logikfunktionen
@@ -875,10 +942,10 @@ Notizen:
#### Dateien hochladen
Der generierte `MetadataApiClient` enthält eine Methode `uploadFile`, um Dateien an Felder des Typs Datei in Ihren Arbeitsbereichsobjekten anzuhängen. Da Standard-GraphQL-Clients Multipart-Datei-Uploads nicht nativ unterstützen, stellt der Client diese dedizierte Methode bereit, die unter der Haube die [GraphQL-Multipart-Anfragespezifikation](https://github.com/jaydenseric/graphql-multipart-request-spec) implementiert.
Der `MetadataApiClient` enthält eine Methode `uploadFile`, um Dateien an Felder des Typs Datei in Ihren Arbeitsbereichsobjekten anzuhängen. Da Standard-GraphQL-Clients Multipart-Datei-Uploads nicht nativ unterstützen, stellt der Client diese dedizierte Methode bereit, die unter der Haube die [GraphQL-Multipart-Anfragespezifikation](https://github.com/jaydenseric/graphql-multipart-request-spec) implementiert.
```typescript
import { MetadataApiClient } from 'twenty-sdk/generated';
import { MetadataApiClient } from 'twenty-sdk/clients';
import * as fs from 'fs';
const metadataClient = new MetadataApiClient();
+2 -2
View File
@@ -149,8 +149,8 @@
"extend": {
"label": "Erweitern",
"groups": {
"extendCapabilities": {
"label": "Funktionen"
"apps": {
"label": "Apps"
}
}
},
@@ -171,7 +171,7 @@ export default defineObject({
Comandi successivi aggiungeranno altri file e cartelle:
* `yarn twenty app:dev` genererà automaticamente due client API tipizzati in `node_modules/twenty-sdk/generated`: `CoreApiClient` (per i dati dell'area di lavoro tramite `/graphql`) e `MetadataApiClient` (per la configurazione dell'area di lavoro e il caricamento di file tramite `/metadata`).
* `yarn twenty app:dev` genererà automaticamente due client API tipizzati in `node_modules/twenty-sdk/clients`: `CoreApiClient` (per i dati dell'area di lavoro tramite `/graphql`) e `MetadataApiClient` (per la configurazione dell'area di lavoro e il caricamento di file tramite `/metadata`).
* `yarn twenty entity:add` will add entity definition files under `src/` for your custom objects, functions, front components, roles, skills, and more.
## Autenticazione
@@ -228,7 +228,7 @@ L'SDK fornisce funzioni helper per definire le entità della tua app. Come descr
| `defineView()` | Definisce viste salvate per gli oggetti |
| `defineNavigationMenuItem()` | Definisce i link di navigazione della barra laterale |
| `defineSkill()` | Define AI agent skills |
| `defineAgent()` | Define AI agents with system prompts |
| `defineAgent()` | Definisci agenti IA con prompt di sistema |
Queste funzioni convalidano la configurazione in fase di build e offrono il completamento automatico nell'IDE e la sicurezza dei tipi.
@@ -321,6 +321,72 @@ Puoi sovrascrivere i campi predefiniti definendo un campo con lo stesso nome nel
ma non è consigliato.
</Note>
### Definire campi sugli oggetti esistenti
Usa `defineField()` per aggiungere campi personalizzati agli oggetti esistenti — sia agli oggetti standard (come `company`, `person`, `opportunity`) sia agli oggetti personalizzati definiti da altre app. Ogni campo risiede nel proprio file e fa riferimento all'oggetto di destinazione tramite il suo `universalIdentifier`.
Per fare riferimento agli oggetti standard, importa `STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS` da `twenty-sdk`. Questa costante fornisce identificatori stabili per tutti gli oggetti integrati e per i relativi campi:
```typescript
// src/fields/apollo-total-funding.field.ts
import {
defineField,
FieldType,
STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS,
} from 'twenty-sdk';
export default defineField({
universalIdentifier: 'c90ae72d-4ddf-4f22-882f-eef98c91e40e',
objectUniversalIdentifier:
STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.company.universalIdentifier,
type: FieldType.CURRENCY,
name: 'apolloTotalFunding',
label: 'Total Funding',
description: 'Total funding raised by the company',
icon: 'IconCash',
});
```
Punti chiave:
* `objectUniversalIdentifier` indica a Twenty a quale oggetto associare il campo. Usa `STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.<objectName>.universalIdentifier` per gli oggetti standard.
* Ogni campo richiede un proprio `universalIdentifier` stabile, un `name`, `type`, `label` e l'`objectUniversalIdentifier` di destinazione.
* Puoi generare nuovi campi usando `yarn twenty entity:add` e scegliendo l'opzione campo.
* `STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS` è anche esportato come `STANDARD_OBJECT` per comodità — entrambi si riferiscono alla stessa costante.
Gli oggetti standard disponibili includono: `attachment`, `blocklist`, `calendarChannel`, `calendarEvent`, `calendarEventParticipant`, `company`, `connectedAccount`, `dashboard`, `favorite`, `favoriteFolder`, `message`, `messageChannel`, `messageParticipant`, `messageThread`, `note`, `noteTarget`, `opportunity`, `person`, `task`, `taskTarget`, `timelineActivity`, `workflow`, `workflowAutomatedTrigger`, `workflowRun`, `workflowVersion` e `workspaceMember`.
Ogni oggetto standard espone anche gli identificatori dei propri campi. Ad esempio, per fare riferimento a un campo specifico su un oggetto standard nelle autorizzazioni dei ruoli:
```typescript
STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.company.fields.name.universalIdentifier
```
#### Campi di relazione su oggetti esistenti
Puoi anche definire campi di relazione che collegano oggetti esistenti ai tuoi oggetti personalizzati:
```typescript
// src/fields/people-on-call-recording.field.ts
import { defineField, FieldType, RelationType, STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS } from 'twenty-sdk';
import { CALL_RECORDING_OBJECT_UNIVERSAL_IDENTIFIER } from 'src/objects/call-recording';
import { CALL_RECORDING_ON_PERSON_ID } from 'src/fields/call-recording-on-person.field';
export default defineField({
universalIdentifier: '4a2b3c4d-5e6f-7a8b-9c0d-1e2f3a4b5c6d',
objectUniversalIdentifier:
CALL_RECORDING_OBJECT_UNIVERSAL_IDENTIFIER,
type: FieldType.RELATION,
name: 'person',
label: 'Person',
relationTargetObjectMetadataUniversalIdentifier:
STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.person.universalIdentifier,
relationTargetFieldMetadataUniversalIdentifier:
CALL_RECORDING_ON_PERSON_ID,
relationType: RelationType.MANY_TO_ONE,
});
```
### Configurazione dell'applicazione (application-config.ts)
Ogni app ha un singolo file `application-config.ts` che descrive:
@@ -434,7 +500,7 @@ Ogni file di funzione usa `defineLogicFunction()` per esportare una configurazio
// src/app/createPostCard.logic-function.ts
import { defineLogicFunction } from 'twenty-sdk';
import type { DatabaseEventPayload, ObjectRecordCreateEvent, CronPayload, RoutePayload } from 'twenty-sdk';
import { CoreApiClient, type Person } from 'twenty-sdk/generated';
import { CoreApiClient, type Person } from 'twenty-sdk/clients';
const handler = async (params: RoutePayload) => {
const client = new CoreApiClient();
@@ -679,7 +745,7 @@ Per contrassegnare una funzione logica come strumento, imposta `isTool: true` e
```typescript
// src/logic-functions/enrich-company.logic-function.ts
import { defineLogicFunction } from 'twenty-sdk';
import { CoreApiClient } from 'twenty-sdk/generated';
import { CoreApiClient } from 'twenty-sdk/clients';
const handler = async (params: { companyName: string; domain?: string }) => {
const client = new CoreApiClient();
@@ -808,7 +874,7 @@ You can create new skills in two ways:
### Agenti
Agents define AI agents with system prompts that can operate within your workspace. Use `defineAgent()` to define agents with built-in validation:
Gli Agenti definiscono agenti IA con prompt di sistema che possono operare all'interno del tuo spazio di lavoro. Usa `defineAgent()` per definire agenti con convalida integrata:
```typescript
// src/agents/example-agent.ts
@@ -830,26 +896,27 @@ export default defineAgent({
Punti chiave:
* `name` is a unique identifier string for the agent (kebab-case recommended).
* `label` is the human-readable display name shown in the UI.
* `prompt` contains the system prompt — this is the instruction text that defines the agent's behavior.
* `icon` (optional) sets the icon displayed in the UI.
* `description` (optional) provides additional context about the agent's purpose.
* `name` è una stringa identificativa univoca per l'agente (kebab-case consigliato).
* `label` è il nome di visualizzazione leggibile mostrato nell'UI.
* `prompt` contiene il prompt di sistema — è il testo di istruzioni che definisce il comportamento dell'agente.
* `icon` (opzionale) imposta l'icona visualizzata nell'UI.
* `description` (opzionale) fornisce contesto aggiuntivo sullo scopo dell'agente.
You can create new agents in two ways:
Puoi creare nuovi agenti in due modi:
* **Scaffolded**: Run `yarn twenty entity:add` and choose the option to add a new agent.
* **Manual**: Create a new file and use `defineAgent()`, following the same pattern.
* **Generata dallo scaffolder**: Esegui `yarn twenty entity:add` e scegli l'opzione per aggiungere un nuovo agente.
* **Manuale**: Crea un nuovo file e usa `defineAgent()`, seguendo lo stesso schema.
### Client tipizzati generati
Due client tipizzati sono generati automaticamente da `yarn twenty app:dev` e salvati in `node_modules/twenty-sdk/generated` in base allo schema della tua area di lavoro:
Due client tipizzati sono generati automaticamente da `yarn twenty app:dev` e salvati in `node_modules/twenty-sdk/clients` in base allo schema della tua area di lavoro:
* **`CoreApiClient`** — interroga l'endpoint `/graphql` per i dati dell'area di lavoro
* **`MetadataApiClient`** — interroga l'endpoint `/metadata` per la configurazione dello spazio di lavoro e il caricamento dei file
```typescript
import { CoreApiClient, MetadataApiClient } from 'twenty-sdk/generated';
import { CoreApiClient } from 'twenty-sdk/clients';
import { MetadataApiClient } from 'twenty-sdk/clients';
const client = new CoreApiClient();
const { me } = await client.query({ me: { id: true, displayName: true } });
@@ -858,7 +925,7 @@ const metadataClient = new MetadataApiClient();
const { currentWorkspace } = await metadataClient.query({ currentWorkspace: { id: true } });
```
Entrambi i client vengono rigenerati automaticamente da `yarn twenty app:dev` ogni volta che i tuoi oggetti o campi cambiano.
`CoreApiClient` viene rigenerato automaticamente da `yarn twenty app:dev` ogni volta che i tuoi oggetti o campi cambiano. `MetadataApiClient` è fornito pronto all'uso con l'SDK.
#### Credenziali di runtime nelle funzioni logiche
@@ -875,10 +942,10 @@ Note:
#### Caricamento dei file
Il `MetadataApiClient` generato include un metodo `uploadFile` per allegare file ai campi di tipo file sugli oggetti del tuo spazio di lavoro. Poiché i client GraphQL standard non supportano nativamente il caricamento di file multipart, il client fornisce questo metodo dedicato che implementa la [specifica della richiesta GraphQL multipart](https://github.com/jaydenseric/graphql-multipart-request-spec) dietro le quinte.
Il `MetadataApiClient` include un metodo `uploadFile` per allegare file ai campi di tipo file sugli oggetti del tuo spazio di lavoro. Poiché i client GraphQL standard non supportano nativamente il caricamento di file multipart, il client fornisce questo metodo dedicato che implementa la [specifica della richiesta GraphQL multipart](https://github.com/jaydenseric/graphql-multipart-request-spec) dietro le quinte.
```typescript
import { MetadataApiClient } from 'twenty-sdk/generated';
import { MetadataApiClient } from 'twenty-sdk/clients';
import * as fs from 'fs';
const metadataClient = new MetadataApiClient();
+2 -2
View File
@@ -149,8 +149,8 @@
"extend": {
"label": "Estendi",
"groups": {
"extendCapabilities": {
"label": "Funzionalità"
"apps": {
"label": "App"
}
}
},
@@ -171,7 +171,7 @@ export default defineObject({
Comandos posteriores adicionarão mais arquivos e pastas:
* `yarn twenty app:dev` irá gerar automaticamente dois clientes de API tipados em `node_modules/twenty-sdk/generated`: `CoreApiClient` (para dados do espaço de trabalho via `/graphql`) e `MetadataApiClient` (para configuração do espaço de trabalho e envio de arquivos via `/metadata`).
* `yarn twenty app:dev` irá gerar automaticamente dois clientes de API tipados em `node_modules/twenty-sdk/clients`: `CoreApiClient` (para dados do espaço de trabalho via `/graphql`) e `MetadataApiClient` (para configuração do espaço de trabalho e envio de ficheiros via `/metadata`).
* `yarn twenty entity:add` adicionará arquivos de definição de entidade em `src/` para seus objetos, funções, componentes de front-end, papéis e habilidades personalizados, entre outros.
## Autenticação
@@ -228,7 +228,7 @@ O SDK fornece funções utilitárias para definir as entidades do seu app. Confo
| `defineView()` | Define visualizações salvas para objetos |
| `defineNavigationMenuItem()` | Define links de navegação da barra lateral |
| `defineSkill()` | Define habilidades de agente de IA |
| `defineAgent()` | Define AI agents with system prompts |
| `defineAgent()` | Defina agentes de IA com prompts do sistema |
Essas funções validam sua configuração em tempo de compilação e oferecem autocompletar na IDE e segurança de tipos.
@@ -321,6 +321,72 @@ Você pode substituir os campos padrão definindo um campo com o mesmo nome no s
mas isso não é recomendado.
</Note>
### Defining fields on existing objects
Use `defineField()` to add custom fields to existing objects — both standard objects (like `company`, `person`, `opportunity`) and custom objects defined by other apps. Each field lives in its own file and references the target object by its `universalIdentifier`.
To reference standard objects, import `STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS` from `twenty-sdk`. This constant provides stable identifiers for all built-in objects and their fields:
```typescript
// src/fields/apollo-total-funding.field.ts
import {
defineField,
FieldType,
STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS,
} from 'twenty-sdk';
export default defineField({
universalIdentifier: 'c90ae72d-4ddf-4f22-882f-eef98c91e40e',
objectUniversalIdentifier:
STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.company.universalIdentifier,
type: FieldType.CURRENCY,
name: 'apolloTotalFunding',
label: 'Total Funding',
description: 'Total funding raised by the company',
icon: 'IconCash',
});
```
Pontos-chave:
* `objectUniversalIdentifier` tells Twenty which object to attach the field to. Use `STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.<objectName>.universalIdentifier` for standard objects.
* Each field requires its own stable `universalIdentifier`, a `name`, `type`, `label`, and the target `objectUniversalIdentifier`.
* You can scaffold new fields using `yarn twenty entity:add` and choosing the field option.
* `STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS` is also exported as `STANDARD_OBJECT` for convenience — both refer to the same constant.
Available standard objects include: `attachment`, `blocklist`, `calendarChannel`, `calendarEvent`, `calendarEventParticipant`, `company`, `connectedAccount`, `dashboard`, `favorite`, `favoriteFolder`, `message`, `messageChannel`, `messageParticipant`, `messageThread`, `note`, `noteTarget`, `opportunity`, `person`, `task`, `taskTarget`, `timelineActivity`, `workflow`, `workflowAutomatedTrigger`, `workflowRun`, `workflowVersion`, and `workspaceMember`.
Each standard object also exposes its field identifiers. For example, to reference a specific field on a standard object in role permissions:
```typescript
STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.company.fields.name.universalIdentifier
```
#### Relation fields on existing objects
You can also define relation fields that link existing objects to your custom objects:
```typescript
// src/fields/people-on-call-recording.field.ts
import { defineField, FieldType, RelationType, STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS } from 'twenty-sdk';
import { CALL_RECORDING_OBJECT_UNIVERSAL_IDENTIFIER } from 'src/objects/call-recording';
import { CALL_RECORDING_ON_PERSON_ID } from 'src/fields/call-recording-on-person.field';
export default defineField({
universalIdentifier: '4a2b3c4d-5e6f-7a8b-9c0d-1e2f3a4b5c6d',
objectUniversalIdentifier:
CALL_RECORDING_OBJECT_UNIVERSAL_IDENTIFIER,
type: FieldType.RELATION,
name: 'person',
label: 'Person',
relationTargetObjectMetadataUniversalIdentifier:
STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.person.universalIdentifier,
relationTargetFieldMetadataUniversalIdentifier:
CALL_RECORDING_ON_PERSON_ID,
relationType: RelationType.MANY_TO_ONE,
});
```
### Configuração do aplicativo (application-config.ts)
Todo aplicativo tem um único arquivo `application-config.ts` que descreve:
@@ -434,7 +500,7 @@ Cada arquivo de função usa `defineLogicFunction()` para exportar uma configura
// src/app/createPostCard.logic-function.ts
import { defineLogicFunction } from 'twenty-sdk';
import type { DatabaseEventPayload, ObjectRecordCreateEvent, CronPayload, RoutePayload } from 'twenty-sdk';
import { CoreApiClient, type Person } from 'twenty-sdk/generated';
import { CoreApiClient, type Person } from 'twenty-sdk/clients';
const handler = async (params: RoutePayload) => {
const client = new CoreApiClient();
@@ -679,7 +745,7 @@ Para marcar uma função lógica como ferramenta, defina `isTool: true` e forne
```typescript
// src/logic-functions/enrich-company.logic-function.ts
import { defineLogicFunction } from 'twenty-sdk';
import { CoreApiClient } from 'twenty-sdk/generated';
import { CoreApiClient } from 'twenty-sdk/clients';
const handler = async (params: { companyName: string; domain?: string }) => {
const client = new CoreApiClient();
@@ -809,7 +875,7 @@ Você pode criar novas habilidades de duas formas:
### Agentes
Agents define AI agents with system prompts that can operate within your workspace. Use `defineAgent()` to define agents with built-in validation:
Agentes definem agentes de IA com prompts do sistema que podem operar no seu espaço de trabalho. Use `defineAgent()` para definir agentes com validação integrada:
```typescript
// src/agents/example-agent.ts
@@ -831,36 +897,36 @@ export default defineAgent({
Pontos-chave:
* `name` is a unique identifier string for the agent (kebab-case recommended).
* `name` é uma string de identificador exclusivo para o agente (recomenda-se kebab-case).
* `label` é o nome de exibição legível por humanos mostrado na UI.
* `prompt` contains the system prompt — this is the instruction text that defines the agent's behavior.
* `prompt` contém o prompt do sistema — este é o texto de instruções que define o comportamento do agente.
* `icon` (opcional) define o ícone exibido na UI.
* `description` (optional) provides additional context about the agent's purpose.
* `description` (opcional) fornece contexto adicional sobre a finalidade do agente.
You can create new agents in two ways:
Você pode criar novos agentes de duas formas:
* **Scaffolded**: Run `yarn twenty entity:add` and choose the option to add a new agent.
* **Manual**: Create a new file and use `defineAgent()`, following the same pattern.
* **Gerado automaticamente**: Execute `yarn twenty entity:add` e escolha a opção para adicionar um novo agente.
* **Manual**: Crie um novo arquivo e use `defineAgent()`, seguindo o mesmo padrão.
### Clientes tipados gerados
Dois clientes tipados são gerados automaticamente pelo `yarn twenty app:dev` e armazenados em `node_modules/twenty-sdk/generated` com base no esquema do seu espaço de trabalho:
Dois clientes tipados são gerados automaticamente pelo `yarn twenty app:dev` e armazenados em `node_modules/twenty-sdk/clients` com base no esquema do seu espaço de trabalho:
* **`CoreApiClient`** — consulta o endpoint `/graphql` para dados do espaço de trabalho
* **`MetadataApiClient`** — consulta o endpoint `/metadata` para obter a configuração do espaço de trabalho e o carregamento de ficheiros
```typescript
import { CoreApiClient, MetadataApiClient } from 'twenty-sdk/generated';
import { CoreApiClient } from 'twenty-sdk/clients';
import { MetadataApiClient } from 'twenty-sdk/clients';
const client = new CoreApiClient();
const { me } = await client.query({ me: { id: true, displayName: true } });
const metadataClient = new MetadataApiClient();
const { currentWorkspace } = await metadataClient.query({ currentWorkspace: { id: true } });
```
Ambos os clientes são regenerados automaticamente pelo `yarn twenty app:dev` sempre que seus objetos ou campos forem alterados.
`CoreApiClient` é regenerado automaticamente pelo `yarn twenty app:dev` sempre que os seus objetos ou campos forem alterados. `MetadataApiClient` é fornecido pré-compilado com o SDK.
#### Credenciais em tempo de execução em funções de lógica
@@ -877,10 +943,10 @@ Notas:
#### Carregamento de ficheiros
O `MetadataApiClient` gerado inclui um método `uploadFile` para anexar ficheiros a campos do tipo ficheiro nos objetos do seu espaço de trabalho. Como os clientes GraphQL padrão não suportam nativamente o carregamento de ficheiros multipart, o cliente fornece este método dedicado que implementa, nos bastidores, a [especificação de pedidos multipart do GraphQL](https://github.com/jaydenseric/graphql-multipart-request-spec).
`MetadataApiClient` inclui um método `uploadFile` para anexar ficheiros a campos do tipo ficheiro nos objetos do seu espaço de trabalho. Como os clientes GraphQL padrão não suportam nativamente o carregamento de ficheiros multipart, o cliente fornece este método dedicado que implementa, nos bastidores, a [especificação de pedidos multipart do GraphQL](https://github.com/jaydenseric/graphql-multipart-request-spec).
```typescript
import { MetadataApiClient } from 'twenty-sdk/generated';
import { MetadataApiClient } from 'twenty-sdk/clients';
import * as fs from 'fs';
const metadataClient = new MetadataApiClient();
@@ -896,7 +962,6 @@ const uploadedFile = await metadataClient.uploadFile(
console.log(uploadedFile);
// { id: '...', path: '...', size: 12345, createdAt: '...', url: 'https://...' }
```
A assinatura do método:
+2 -2
View File
@@ -149,8 +149,8 @@
"extend": {
"label": "Extend",
"groups": {
"extendCapabilities": {
"label": "Capabilities"
"apps": {
"label": "Aplicativos"
}
}
},
@@ -171,7 +171,7 @@ export default defineObject({
Comenzile ulterioare vor adăuga mai multe fișiere și foldere:
* `yarn twenty app:dev` will auto-generate two typed API clients in `node_modules/twenty-sdk/generated`: `CoreApiClient` (for workspace data via `/graphql`) and `MetadataApiClient` (for workspace configuration and file uploads via `/metadata`).
* `yarn twenty app:dev` va genera automat doi clienți API tipizați în `node_modules/twenty-sdk/clients`: `CoreApiClient` (pentru datele spațiului de lucru prin `/graphql`) și `MetadataApiClient` (pentru configurarea spațiului de lucru și încărcarea fișierelor prin `/metadata`).
* `yarn twenty entity:add` va adăuga fișiere de definire a entităților în `src/` pentru obiectele, funcțiile, componentele front-end, rolurile, abilitățile și altele.
## Autentificare
@@ -228,7 +228,7 @@ SDK-ul oferă funcții ajutătoare pentru definirea entităților aplicației. D
| `defineView()` | Definește vizualizări salvate pentru obiecte |
| `defineNavigationMenuItem()` | Definește linkuri de navigare în bara laterală |
| `defineSkill()` | Definiți abilități pentru agentul AI |
| `defineAgent()` | Define AI agents with system prompts |
| `defineAgent()` | Definiți agenți AI cu prompturi de sistem |
Aceste funcții validează configurația în timpul build-ului și oferă completare automată în IDE și siguranța tipurilor.
@@ -321,6 +321,72 @@ Puteți suprascrie câmpurile implicite definind un câmp cu același nume în t
dar acest lucru nu este recomandat.
</Note>
### Definirea câmpurilor pe obiecte existente
Folosiți `defineField()` pentru a adăuga câmpuri personalizate la obiectele existente — atât obiecte standard (precum `company`, `person`, `opportunity`), cât și obiecte personalizate definite de alte aplicații. Fiecare câmp se află în propriul fișier și face referire la obiectul țintă prin `universalIdentifier`.
Pentru a face referire la obiectele standard, importați `STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS` din `twenty-sdk`. Această constantă furnizează identificatori stabili pentru toate obiectele integrate și câmpurile lor:
```typescript
// src/fields/apollo-total-funding.field.ts
import {
defineField,
FieldType,
STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS,
} from 'twenty-sdk';
export default defineField({
universalIdentifier: 'c90ae72d-4ddf-4f22-882f-eef98c91e40e',
objectUniversalIdentifier:
STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.company.universalIdentifier,
type: FieldType.CURRENCY,
name: 'apolloTotalFunding',
label: 'Total Funding',
description: 'Total funding raised by the company',
icon: 'IconCash',
});
```
Puncte cheie:
* `objectUniversalIdentifier` îi indică lui Twenty la care obiect să atașeze câmpul. Folosiți `STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.<objectName>.universalIdentifier` pentru obiectele standard.
* Fiecare câmp necesită propriul `universalIdentifier` stabil, un `name`, `type`, `label` și `objectUniversalIdentifier` țintă.
* Puteți genera câmpuri noi folosind `yarn twenty entity:add` și alegând opțiunea pentru câmp.
* `STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS` este exportată și ca `STANDARD_OBJECT` pentru comoditate — ambele se referă la aceeași constantă.
Obiectele standard disponibile includ: `attachment`, `blocklist`, `calendarChannel`, `calendarEvent`, `calendarEventParticipant`, `company`, `connectedAccount`, `dashboard`, `favorite`, `favoriteFolder`, `message`, `messageChannel`, `messageParticipant`, `messageThread`, `note`, `noteTarget`, `opportunity`, `person`, `task`, `taskTarget`, `timelineActivity`, `workflow`, `workflowAutomatedTrigger`, `workflowRun`, `workflowVersion` și `workspaceMember`.
Fiecare obiect standard expune, de asemenea, identificatorii câmpurilor sale. De exemplu, pentru a face referire la un câmp specific pe un obiect standard în permisiunile de rol:
```typescript
STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.company.fields.name.universalIdentifier
```
#### Câmpuri de relație pe obiecte existente
Puteți defini, de asemenea, câmpuri de relație care leagă obiectele existente de obiectele dvs. personalizate:
```typescript
// src/fields/people-on-call-recording.field.ts
import { defineField, FieldType, RelationType, STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS } from 'twenty-sdk';
import { CALL_RECORDING_OBJECT_UNIVERSAL_IDENTIFIER } from 'src/objects/call-recording';
import { CALL_RECORDING_ON_PERSON_ID } from 'src/fields/call-recording-on-person.field';
export default defineField({
universalIdentifier: '4a2b3c4d-5e6f-7a8b-9c0d-1e2f3a4b5c6d',
objectUniversalIdentifier:
CALL_RECORDING_OBJECT_UNIVERSAL_IDENTIFIER,
type: FieldType.RELATION,
name: 'person',
label: 'Person',
relationTargetObjectMetadataUniversalIdentifier:
STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.person.universalIdentifier,
relationTargetFieldMetadataUniversalIdentifier:
CALL_RECORDING_ON_PERSON_ID,
relationType: RelationType.MANY_TO_ONE,
});
```
### Configurația aplicației (application-config.ts)
Fiecare aplicație are un singur fișier `application-config.ts` care descrie:
@@ -434,7 +500,7 @@ Fiecare fișier de funcție folosește `defineLogicFunction()` pentru a exporta
// src/app/createPostCard.logic-function.ts
import { defineLogicFunction } from 'twenty-sdk';
import type { DatabaseEventPayload, ObjectRecordCreateEvent, CronPayload, RoutePayload } from 'twenty-sdk';
import { CoreApiClient, type Person } from 'twenty-sdk/generated';
import { CoreApiClient, type Person } from 'twenty-sdk/clients';
const handler = async (params: RoutePayload) => {
const client = new CoreApiClient();
@@ -679,7 +745,7 @@ Pentru a marca o funcție logică drept instrument, setați `isTool: true` și f
```typescript
// src/logic-functions/enrich-company.logic-function.ts
import { defineLogicFunction } from 'twenty-sdk';
import { CoreApiClient } from 'twenty-sdk/generated';
import { CoreApiClient } from 'twenty-sdk/clients';
const handler = async (params: { companyName: string; domain?: string }) => {
const client = new CoreApiClient();
@@ -808,7 +874,7 @@ Puteți crea abilități noi în două moduri:
### Agenți
Agents define AI agents with system prompts that can operate within your workspace. Use `defineAgent()` to define agents with built-in validation:
Agenții sunt agenți AI definiți cu prompturi de sistem, care pot funcționa în spațiul dvs. de lucru. Utilizați `defineAgent()` pentru a defini agenți cu validare încorporată:
```typescript
// src/agents/example-agent.ts
@@ -830,26 +896,27 @@ export default defineAgent({
Puncte cheie:
* `name` is a unique identifier string for the agent (kebab-case recommended).
* `name` este un șir identificator unic pentru agent (se recomandă kebab-case).
* `label` este numele lizibil afișat în interfața cu utilizatorul (UI).
* `prompt` contains the system prompt — this is the instruction text that defines the agent's behavior.
* `prompt` conține promptul de sistem — acesta este textul de instrucțiuni care definește comportamentul agentului.
* `icon` (opțional) setează pictograma afișată în UI.
* `description` (optional) provides additional context about the agent's purpose.
* `description` (opțional) oferă context suplimentar despre scopul agentului.
You can create new agents in two ways:
Puteți crea agenți noi în două moduri:
* **Scaffolded**: Run `yarn twenty entity:add` and choose the option to add a new agent.
* **Manual**: Create a new file and use `defineAgent()`, following the same pattern.
* **Generat**: Rulați `yarn twenty entity:add` și alegeți opțiunea de a adăuga un agent nou.
* **Manual**: Creați un fișier nou și folosiți `defineAgent()`, urmând același model.
### Generated typed clients
Two typed clients are auto-generated by `yarn twenty app:dev` and stored in `node_modules/twenty-sdk/generated` based on your workspace schema:
Doi clienți tipizați sunt generați automat de `yarn twenty app:dev` și stocați în `node_modules/twenty-sdk/clients`, pe baza schemei spațiului tău de lucru:
* **`CoreApiClient`** — queries the `/graphql` endpoint for workspace data
* **`MetadataApiClient`** — interoghează endpointul `/metadata` pentru configurarea spațiului de lucru și încărcarea fișierelor
```typescript
import { CoreApiClient, MetadataApiClient } from 'twenty-sdk/generated';
import { CoreApiClient } from 'twenty-sdk/clients';
import { MetadataApiClient } from 'twenty-sdk/clients';
const client = new CoreApiClient();
const { me } = await client.query({ me: { id: true, displayName: true } });
@@ -858,7 +925,7 @@ const metadataClient = new MetadataApiClient();
const { currentWorkspace } = await metadataClient.query({ currentWorkspace: { id: true } });
```
Ambii clienți sunt regenerați automat de `yarn twenty app:dev` ori de câte ori obiectele sau câmpurile tale se schimbă.
`CoreApiClient` este regenerat automat de `yarn twenty app:dev` ori de câte ori obiectele sau câmpurile tale se schimbă. `MetadataApiClient` este livrat preconstruit împreună cu SDK-ul.
#### Acreditări la runtime în funcțiile de logică
@@ -875,10 +942,10 @@ Notițe:
#### Încărcarea fișierelor
Clientul `MetadataApiClient` generat include o metodă `uploadFile` pentru atașarea fișierelor la câmpuri de tip fișier ale obiectelor din spațiul tău de lucru. Deoarece clienții GraphQL standard nu acceptă în mod nativ încărcarea fișierelor multipart, clientul oferă această metodă dedicată care implementează, sub capotă, [specificația cererilor GraphQL multipart](https://github.com/jaydenseric/graphql-multipart-request-spec).
`MetadataApiClient` include o metodă `uploadFile` pentru atașarea fișierelor la câmpuri de tip fișier ale obiectelor din spațiul tău de lucru. Deoarece clienții GraphQL standard nu acceptă în mod nativ încărcarea fișierelor multipart, clientul oferă această metodă dedicată care implementează, sub capotă, [specificația cererilor GraphQL multipart](https://github.com/jaydenseric/graphql-multipart-request-spec).
```typescript
import { MetadataApiClient } from 'twenty-sdk/generated';
import { MetadataApiClient } from 'twenty-sdk/clients';
import * as fs from 'fs';
const metadataClient = new MetadataApiClient();
+2 -2
View File
@@ -149,8 +149,8 @@
"extend": {
"label": "Extend",
"groups": {
"extendCapabilities": {
"label": "Capabilities"
"apps": {
"label": "Aplicații"
}
}
},
@@ -171,7 +171,7 @@ export default defineObject({
Позднее команды добавят больше файлов и папок:
* `yarn twenty app:dev` автоматически сгенерирует два типизированных клиента API в `node_modules/twenty-sdk/generated`: `CoreApiClient` (для данных рабочего пространства через `/graphql`) и `MetadataApiClient` (для конфигурации рабочего пространства и загрузки файлов через `/metadata`).
* `yarn twenty app:dev` автоматически сгенерирует два типизированных клиента API в `node_modules/twenty-sdk/clients`: `CoreApiClient` (для данных рабочего пространства через `/graphql`) и `MetadataApiClient` (для конфигурации рабочего пространства и загрузки файлов через `/metadata`).
* `yarn twenty entity:add` добавит файлы определений сущностей в `src/` для ваших пользовательских объектов, функций, фронтенд-компонентов, ролей, навыков и многого другого.
## Аутентификация
@@ -228,7 +228,7 @@ SDK предоставляет вспомогательные функции д
| `defineView()` | Определяйте сохранённые представления для объектов |
| `defineNavigationMenuItem()` | Определяйте ссылки боковой панели навигации |
| `defineSkill()` | Определение навыков агента ИИ |
| `defineAgent()` | Define AI agents with system prompts |
| `defineAgent()` | Определяйте ИИ-агентов с системными промптами |
Эти функции проверяют вашу конфигурацию на этапе сборки и обеспечивают автодополнение в IDE и безопасность типов.
@@ -321,6 +321,72 @@ export default defineObject({
но это не рекомендуется.
</Note>
### Defining fields on existing objects
Use `defineField()` to add custom fields to existing objects — both standard objects (like `company`, `person`, `opportunity`) and custom objects defined by other apps. Each field lives in its own file and references the target object by its `universalIdentifier`.
To reference standard objects, import `STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS` from `twenty-sdk`. This constant provides stable identifiers for all built-in objects and their fields:
```typescript
// src/fields/apollo-total-funding.field.ts
import {
defineField,
FieldType,
STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS,
} from 'twenty-sdk';
export default defineField({
universalIdentifier: 'c90ae72d-4ddf-4f22-882f-eef98c91e40e',
objectUniversalIdentifier:
STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.company.universalIdentifier,
type: FieldType.CURRENCY,
name: 'apolloTotalFunding',
label: 'Total Funding',
description: 'Total funding raised by the company',
icon: 'IconCash',
});
```
Основные моменты:
* `objectUniversalIdentifier` tells Twenty which object to attach the field to. Use `STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.<objectName>.universalIdentifier` for standard objects.
* Each field requires its own stable `universalIdentifier`, a `name`, `type`, `label`, and the target `objectUniversalIdentifier`.
* You can scaffold new fields using `yarn twenty entity:add` and choosing the field option.
* `STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS` is also exported as `STANDARD_OBJECT` for convenience — both refer to the same constant.
Available standard objects include: `attachment`, `blocklist`, `calendarChannel`, `calendarEvent`, `calendarEventParticipant`, `company`, `connectedAccount`, `dashboard`, `favorite`, `favoriteFolder`, `message`, `messageChannel`, `messageParticipant`, `messageThread`, `note`, `noteTarget`, `opportunity`, `person`, `task`, `taskTarget`, `timelineActivity`, `workflow`, `workflowAutomatedTrigger`, `workflowRun`, `workflowVersion`, and `workspaceMember`.
Each standard object also exposes its field identifiers. For example, to reference a specific field on a standard object in role permissions:
```typescript
STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.company.fields.name.universalIdentifier
```
#### Relation fields on existing objects
You can also define relation fields that link existing objects to your custom objects:
```typescript
// src/fields/people-on-call-recording.field.ts
import { defineField, FieldType, RelationType, STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS } from 'twenty-sdk';
import { CALL_RECORDING_OBJECT_UNIVERSAL_IDENTIFIER } from 'src/objects/call-recording';
import { CALL_RECORDING_ON_PERSON_ID } from 'src/fields/call-recording-on-person.field';
export default defineField({
universalIdentifier: '4a2b3c4d-5e6f-7a8b-9c0d-1e2f3a4b5c6d',
objectUniversalIdentifier:
CALL_RECORDING_OBJECT_UNIVERSAL_IDENTIFIER,
type: FieldType.RELATION,
name: 'person',
label: 'Person',
relationTargetObjectMetadataUniversalIdentifier:
STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.person.universalIdentifier,
relationTargetFieldMetadataUniversalIdentifier:
CALL_RECORDING_ON_PERSON_ID,
relationType: RelationType.MANY_TO_ONE,
});
```
### Конфигурация приложения (application-config.ts)
У каждого приложения есть единственный файл `application-config.ts`, который описывает:
@@ -434,7 +500,7 @@ export default defineRole({
// src/app/createPostCard.logic-function.ts
import { defineLogicFunction } from 'twenty-sdk';
import type { DatabaseEventPayload, ObjectRecordCreateEvent, CronPayload, RoutePayload } from 'twenty-sdk';
import { CoreApiClient, type Person } from 'twenty-sdk/generated';
import { CoreApiClient, type Person } from 'twenty-sdk/clients';
const handler = async (params: RoutePayload) => {
const client = new CoreApiClient();
@@ -679,7 +745,7 @@ const handler = async (event: RoutePayload) => {
```typescript
// src/logic-functions/enrich-company.logic-function.ts
import { defineLogicFunction } from 'twenty-sdk';
import { CoreApiClient } from 'twenty-sdk/generated';
import { CoreApiClient } from 'twenty-sdk/clients';
const handler = async (params: { companyName: string; domain?: string }) => {
const client = new CoreApiClient();
@@ -720,7 +786,7 @@ export default defineLogicFunction({
},
required: ['companyName'],
},
});},{
});
```
Основные моменты:
@@ -808,7 +874,7 @@ export default defineSkill({
### Агенты
Agents define AI agents with system prompts that can operate within your workspace. Use `defineAgent()` to define agents with built-in validation:
Agents позволяют определять ИИ-агентов с системными промптами, которые могут работать в вашем рабочем пространстве. Используйте `defineAgent()` для определения агентов со встроенной валидацией:
```typescript
// src/agents/example-agent.ts
@@ -830,26 +896,27 @@ export default defineAgent({
Основные моменты:
* `name` is a unique identifier string for the agent (kebab-case recommended).
* `name` — уникальная строка-идентификатор агента (рекомендуется kebab-case).
* `label` — читаемое человеком отображаемое имя, показываемое в UI.
* `prompt` contains the system prompt — this is the instruction text that defines the agent's behavior.
* `prompt` содержит системный промпт — это текст инструкции, который определяет поведение агента.
* `icon` (необязательно) задаёт значок, отображаемый в UI.
* `description` (optional) provides additional context about the agent's purpose.
* `description` (необязательно) предоставляет дополнительный контекст о назначении агента.
You can create new agents in two ways:
Вы можете создать новых агентов двумя способами:
* **Scaffolded**: Run `yarn twenty entity:add` and choose the option to add a new agent.
* **Manual**: Create a new file and use `defineAgent()`, following the same pattern.
* **Сгенерировано**: Запустите `yarn twenty entity:add` и выберите опцию добавления нового агента.
* **Вручную**: Создайте новый файл и используйте `defineAgent()`, следуя тому же шаблону.
### Сгенерированные типизированные клиенты
Два типизированных клиента автоматически генерируются с помощью `yarn twenty app:dev` и сохраняются в `node_modules/twenty-sdk/generated` на основе схемы вашего рабочего пространства:
Два типизированных клиента автоматически генерируются с помощью `yarn twenty app:dev` и сохраняются в `node_modules/twenty-sdk/clients` на основе схемы вашего рабочего пространства:
* **`CoreApiClient`** — выполняет запросы к конечной точке `/graphql` для получения данных рабочего пространства
* **`MetadataApiClient`** — выполняет запросы к эндпоинту `/metadata` для получения конфигурации рабочего пространства и загрузки файлов.
```typescript
import { CoreApiClient, MetadataApiClient } from 'twenty-sdk/generated';
import { CoreApiClient } from 'twenty-sdk/clients';
import { MetadataApiClient } from 'twenty-sdk/clients';
const client = new CoreApiClient();
const { me } = await client.query({ me: { id: true, displayName: true } });
@@ -858,7 +925,7 @@ const metadataClient = new MetadataApiClient();
const { currentWorkspace } = await metadataClient.query({ currentWorkspace: { id: true } });
```
Оба клиента автоматически перегенерируются с помощью `yarn twenty app:dev` при изменении ваших объектов или полей.
`CoreApiClient` автоматически перегенерируется с помощью `yarn twenty app:dev` при изменении ваших объектов или полей. `MetadataApiClient` поставляется готовым в составе SDK.
#### Учётные данные времени выполнения в логических функциях
@@ -875,10 +942,10 @@ const { currentWorkspace } = await metadataClient.query({ currentWorkspace: { id
#### Загрузка файлов
Сгенерированный `MetadataApiClient` включает метод `uploadFile` для прикрепления файлов к полям типа «файл» в объектах вашего рабочего пространства. Поскольку стандартные клиенты GraphQL изначально не поддерживают многочастовую загрузку файлов, клиент предоставляет специальный метод, который под капотом реализует [спецификацию многочастных запросов GraphQL](https://github.com/jaydenseric/graphql-multipart-request-spec).
`MetadataApiClient` включает метод `uploadFile` для прикрепления файлов к полям типа «файл» в объектах вашего рабочего пространства. Поскольку стандартные клиенты GraphQL изначально не поддерживают многочастовую загрузку файлов, клиент предоставляет специальный метод, который под капотом реализует [спецификацию многочастных запросов GraphQL](https://github.com/jaydenseric/graphql-multipart-request-spec).
```typescript
import { MetadataApiClient } from 'twenty-sdk/generated';
import { MetadataApiClient } from 'twenty-sdk/clients';
import * as fs from 'fs';
const metadataClient = new MetadataApiClient();
+2 -2
View File
@@ -149,8 +149,8 @@
"extend": {
"label": "Расширяйте",
"groups": {
"extendCapabilities": {
"label": "Возможности"
"apps": {
"label": "Приложения"
}
}
},
@@ -15,7 +15,7 @@ Uygulamalar, Twenty özelleştirmelerini **kod olarak** oluşturup yönetmenizi
* Özel nesneleri ve alanları kod olarak tanımlayın (yönetilen veri modeli)
* Özel tetikleyicilerle mantık fonksiyonları oluşturun
* Define skills and agents for AI
* Yapay zekâ için yetenekleri ve ajanları tanımlayın
* Aynı uygulamayı birden çok çalışma alanına dağıtın
## Ön Gereksinimler
@@ -39,10 +39,10 @@ yarn twenty app:dev
İskelet oluşturucu, hangi örnek dosyaların dahil edileceğini kontrol etmek için iki modu destekler:
```bash filename="Terminal"
# Default (exhaustive): all examples (object, field, logic function, front component, view, navigation menu item, skill, agent)
# Varsayılan (kapsamlı): tüm örnekler (nesne, alan, mantık fonksiyonu, ön bileşen, görünüm, gezinme menüsü öğesi, yetenek, ajan)
npx create-twenty-app@latest my-app
# Minimal: only core files (application-config.ts and default-role.ts)
# Minimal: yalnızca çekirdek dosyalar (application-config.ts ve default-role.ts)
npx create-twenty-app@latest my-app --minimal
```
@@ -96,29 +96,29 @@ my-twenty-app/
.oxlintrc.json
tsconfig.json
README.md
public/ # Public assets folder (images, fonts, etc.)
public/ # Genel varlıklar klasörü (görseller, yazı tipleri vb.)
src/
├── application-config.ts # Required - main application configuration
├── application-config.ts # Gerekli - ana uygulama yapılandırması
├── roles/
│ └── default-role.ts # Default role for logic functions
│ └── default-role.ts # Mantık fonksiyonları için varsayılan rol
├── objects/
│ └── example-object.ts # Example custom object definition
│ └── example-object.ts # Örnek özel nesne tanımı
├── fields/
│ └── example-field.ts # Example standalone field definition
│ └── example-field.ts # Örnek bağımsız alan tanımı
├── logic-functions/
│ ├── hello-world.ts # Example logic function
│ ├── pre-install.ts # Pre-install logic function
│ └── post-install.ts # Post-install logic function
│ ├── hello-world.ts # Örnek mantık fonksiyonu
│ ├── pre-install.ts # Kurulum öncesi mantık fonksiyonu
│ └── post-install.ts # Kurulum sonrası mantık fonksiyonu
├── front-components/
│ └── hello-world.tsx # Example front component
│ └── hello-world.tsx # Örnek ön bileşen
├── views/
│ └── example-view.ts # Example saved view definition
│ └── example-view.ts # Örnek kaydedilmiş görünüm tanımı
├── navigation-menu-items/
│ └── example-navigation-menu-item.ts # Example sidebar navigation link
│ └── example-navigation-menu-item.ts # Örnek kenar çubuğu gezinme bağlantısı
├── skills/
│ └── example-skill.ts # Example AI agent skill definition
│ └── example-skill.ts # Örnek yapay zekâ ajanı yetenek tanımı
└── agents/
└── example-agent.ts # Example AI agent definition
└── example-agent.ts # Örnek yapay zekâ ajanı tanımı
```
`--minimal` ile yalnızca çekirdek dosyalar oluşturulur (`application-config.ts`, `roles/default-role.ts`, `logic-functions/pre-install.ts` ve `logic-functions/post-install.ts`).
@@ -150,7 +150,7 @@ SDK, TypeScript dosyalarınızı **`export default define<Entity>({...})`** ça
| `defineView()` | Kaydedilmiş görünüm tanımları |
| `defineNavigationMenuItem()` | Gezinme menüsü öğesi tanımları |
| `defineSkill()` | Yapay zekâ ajanı yetenek tanımları |
| `defineAgent()` | AI agent definitions |
| `defineAgent()` | Yapay zekâ ajanı tanımları |
<Note>
**Dosya adlandırma esnektir.** Varlık algılama AST tabanlıdır — SDK, kaynak dosyalarınızı `export default define<Entity>({...})` desenini bulmak için tarar. Dosyalarınızı ve klasörlerinizi dilediğiniz gibi düzenleyebilirsiniz. Varlık türüne göre gruplama (örn. `logic-functions/`, `roles/`) bir gereklilik değil, yalnızca kod organizasyonu için bir gelenektir.
@@ -171,7 +171,7 @@ export default defineObject({
İlerideki komutlar daha fazla dosya ve klasör ekleyecektir:
* `yarn twenty app:dev`, `node_modules/twenty-sdk/generated` içinde iki tiplendirilmiş API istemcisini otomatik olarak oluşturur: `CoreApiClient` (`/graphql` üzerinden çalışma alanı verileri için) ve `MetadataApiClient` (çalışma alanı yapılandırması ve `/metadata` üzerinden dosya yüklemeleri için).
* `yarn twenty app:dev`, `node_modules/twenty-sdk/clients` içinde iki tiplendirilmiş API istemcisini otomatik olarak oluşturur: `CoreApiClient` (`/graphql` üzerinden çalışma alanı verileri için) ve `MetadataApiClient` (çalışma alanı yapılandırması ve `/metadata` üzerinden dosya yüklemeleri için).
* `yarn twenty entity:add`, özel nesneleriniz, fonksiyonlarınız, ön bileşenleriniz, rolleriniz, yetenekleriniz ve daha fazlası için `src/` altında varlık tanım dosyaları ekler.
## Kimlik Doğrulama
@@ -228,7 +228,7 @@ SDK, uygulama varlıklarınızı tanımlamak için yardımcı fonksiyonlar sağl
| `defineView()` | Nesneler için kaydedilmiş görünümler tanımlayın |
| `defineNavigationMenuItem()` | Kenar çubuğu gezinme bağlantılarını tanımlayın |
| `defineSkill()` | Yapay zekâ ajanı yeteneklerini tanımlayın |
| `defineAgent()` | Define AI agents with system prompts |
| `defineAgent()` | Sistem istemleriyle yapay zekâ ajanları tanımlayın |
Bu fonksiyonlar, derleme zamanında yapılandırmanızı doğrular ve IDE otomatik tamamlama ile tür güvenliği sağlar.
@@ -321,6 +321,72 @@ Bunları `fields` dizinizde tanımlamanız gerekmez — yalnızca özel alanlar
ancak bu önerilmez.
</Note>
### Defining fields on existing objects
Use `defineField()` to add custom fields to existing objects — both standard objects (like `company`, `person`, `opportunity`) and custom objects defined by other apps. Each field lives in its own file and references the target object by its `universalIdentifier`.
To reference standard objects, import `STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS` from `twenty-sdk`. This constant provides stable identifiers for all built-in objects and their fields:
```typescript
// src/fields/apollo-total-funding.field.ts
import {
defineField,
FieldType,
STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS,
} from 'twenty-sdk';
export default defineField({
universalIdentifier: 'c90ae72d-4ddf-4f22-882f-eef98c91e40e',
objectUniversalIdentifier:
STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.company.universalIdentifier,
type: FieldType.CURRENCY,
name: 'apolloTotalFunding',
label: 'Total Funding',
description: 'Total funding raised by the company',
icon: 'IconCash',
});
```
Önemli noktalar:
* `objectUniversalIdentifier` tells Twenty which object to attach the field to. Use `STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.<objectName>.universalIdentifier` for standard objects.
* Each field requires its own stable `universalIdentifier`, a `name`, `type`, `label`, and the target `objectUniversalIdentifier`.
* You can scaffold new fields using `yarn twenty entity:add` and choosing the field option.
* `STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS` is also exported as `STANDARD_OBJECT` for convenience — both refer to the same constant.
Available standard objects include: `attachment`, `blocklist`, `calendarChannel`, `calendarEvent`, `calendarEventParticipant`, `company`, `connectedAccount`, `dashboard`, `favorite`, `favoriteFolder`, `message`, `messageChannel`, `messageParticipant`, `messageThread`, `note`, `noteTarget`, `opportunity`, `person`, `task`, `taskTarget`, `timelineActivity`, `workflow`, `workflowAutomatedTrigger`, `workflowRun`, `workflowVersion`, and `workspaceMember`.
Each standard object also exposes its field identifiers. For example, to reference a specific field on a standard object in role permissions:
```typescript
STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.company.fields.name.universalIdentifier
```
#### Relation fields on existing objects
You can also define relation fields that link existing objects to your custom objects:
```typescript
// src/fields/people-on-call-recording.field.ts
import { defineField, FieldType, RelationType, STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS } from 'twenty-sdk';
import { CALL_RECORDING_OBJECT_UNIVERSAL_IDENTIFIER } from 'src/objects/call-recording';
import { CALL_RECORDING_ON_PERSON_ID } from 'src/fields/call-recording-on-person.field';
export default defineField({
universalIdentifier: '4a2b3c4d-5e6f-7a8b-9c0d-1e2f3a4b5c6d',
objectUniversalIdentifier:
CALL_RECORDING_OBJECT_UNIVERSAL_IDENTIFIER,
type: FieldType.RELATION,
name: 'person',
label: 'Person',
relationTargetObjectMetadataUniversalIdentifier:
STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.person.universalIdentifier,
relationTargetFieldMetadataUniversalIdentifier:
CALL_RECORDING_ON_PERSON_ID,
relationType: RelationType.MANY_TO_ONE,
});
```
### Uygulama yapılandırması (application-config.ts)
Her uygulamanın aşağıdakileri açıklayan tek bir `application-config.ts` dosyası vardır:
@@ -434,7 +500,7 @@ Her fonksiyon dosyası, bir işleyici ve isteğe bağlı tetikleyiciler içeren
// src/app/createPostCard.logic-function.ts
import { defineLogicFunction } from 'twenty-sdk';
import type { DatabaseEventPayload, ObjectRecordCreateEvent, CronPayload, RoutePayload } from 'twenty-sdk';
import { CoreApiClient, type Person } from 'twenty-sdk/generated';
import { CoreApiClient, type Person } from 'twenty-sdk/clients';
const handler = async (params: RoutePayload) => {
const client = new CoreApiClient();
@@ -679,7 +745,7 @@ Bir mantık işlevini bir araç olarak işaretlemek için `isTool: true` olarak
```typescript
// src/logic-functions/enrich-company.logic-function.ts
import { defineLogicFunction } from 'twenty-sdk';
import { CoreApiClient } from 'twenty-sdk/generated';
import { CoreApiClient } from 'twenty-sdk/clients';
const handler = async (params: { companyName: string; domain?: string }) => {
const client = new CoreApiClient();
@@ -808,7 +874,7 @@ Yeni yetenekleri iki şekilde oluşturabilirsiniz:
### Temsilciler
Agents define AI agents with system prompts that can operate within your workspace. Use `defineAgent()` to define agents with built-in validation:
Ajanlar, çalışma alanınızda çalışabilen sistem istemlerine sahip yapay zekâ ajanlarını tanımlar. Yerleşik doğrulamayla ajanları tanımlamak için `defineAgent()` kullanın:
```typescript
// src/agents/example-agent.ts
@@ -830,26 +896,27 @@ export default defineAgent({
Önemli noktalar:
* `name` is a unique identifier string for the agent (kebab-case recommended).
* `name`, ajan için benzersiz bir tanımlayıcı dizedir (kebab-case önerilir).
* `label`, UI'de gösterilen, insan tarafından okunabilir addır.
* `prompt` contains the system prompt — this is the instruction text that defines the agent's behavior.
* `prompt`, sistem istemini içerir — bu, ajanın davranışını tanımlayan talimat metnidir.
* `icon` (isteğe bağlı), UI'de gösterilen simgeyi ayarlar.
* `description` (optional) provides additional context about the agent's purpose.
* `description` (isteğe bağlı), ajanın amacı hakkında ek bağlam sağlar.
You can create new agents in two ways:
Yeni ajanları iki şekilde oluşturabilirsiniz:
* **Scaffolded**: Run `yarn twenty entity:add` and choose the option to add a new agent.
* **Manual**: Create a new file and use `defineAgent()`, following the same pattern.
* **Şablondan**: `yarn twenty entity:add` komutunu çalıştırın ve yeni bir ajan ekleme seçeneğini seçin.
* **Manuel**: Yeni bir dosya oluşturun ve aynı deseni izleyerek `defineAgent()` kullanın.
### Oluşturulan tiplendirilmiş istemciler
Çalışma alanı şemanıza göre `yarn twenty app:dev` tarafından iki tiplendirilmiş istemci otomatik olarak oluşturulur ve `node_modules/twenty-sdk/generated` içine kaydedilir:
Çalışma alanı şemanıza göre `yarn twenty app:dev` tarafından iki tiplendirilmiş istemci otomatik olarak oluşturulur ve `node_modules/twenty-sdk/clients` içine kaydedilir:
* **`CoreApiClient`** — çalışma alanı verileri için `/graphql` uç noktasını sorgular
* **`MetadataApiClient`** — çalışma alanı yapılandırması ve dosya yüklemeleri için `/metadata` uç noktasını sorgular.
```typescript
import { CoreApiClient, MetadataApiClient } from 'twenty-sdk/generated';
import { CoreApiClient } from 'twenty-sdk/clients';
import { MetadataApiClient } from 'twenty-sdk/clients';
const client = new CoreApiClient();
const { me } = await client.query({ me: { id: true, displayName: true } });
@@ -858,7 +925,7 @@ const metadataClient = new MetadataApiClient();
const { currentWorkspace } = await metadataClient.query({ currentWorkspace: { id: true } });
```
Her iki istemci de, nesneleriniz veya alanlarınız değiştiğinde, `yarn twenty app:dev` tarafından otomatik olarak yeniden oluşturulur.
`CoreApiClient`, nesneleriniz veya alanlarınız değiştiğinde `yarn twenty app:dev` tarafından otomatik olarak yeniden oluşturulur. `MetadataApiClient`, SDK ile birlikte önceden hazırlanmış olarak gelir.
#### Mantık fonksiyonlarında çalışma zamanı kimlik bilgileri
@@ -875,10 +942,10 @@ Notlar:
#### Dosya yükleme
Oluşturulan `MetadataApiClient`, çalışma alanı nesnelerinizdeki dosya türündeki alanlara dosya eklemek için bir `uploadFile` yöntemi içerir. Standart GraphQL istemcileri çok parçalı dosya yüklemelerini yerel olarak desteklemediğinden, istemci arka planda [GraphQL çok parçalı istek belirtimi](https://github.com/jaydenseric/graphql-multipart-request-spec) uygulayan bu özel yöntemi sağlar.
`MetadataApiClient`, çalışma alanı nesnelerinizdeki dosya türündeki alanlara dosya eklemek için bir `uploadFile` yöntemi içerir. Standart GraphQL istemcileri çok parçalı dosya yüklemelerini yerel olarak desteklemediğinden, istemci arka planda [GraphQL çok parçalı istek belirtimi](https://github.com/jaydenseric/graphql-multipart-request-spec) uygulayan bu özel yöntemi sağlar.
```typescript
import { MetadataApiClient } from 'twenty-sdk/generated';
import { MetadataApiClient } from 'twenty-sdk/clients';
import * as fs from 'fs';
const metadataClient = new MetadataApiClient();
+2 -2
View File
@@ -149,8 +149,8 @@
"extend": {
"label": "Genişlet",
"groups": {
"extendCapabilities": {
"label": "Yetkinlikler"
"apps": {
"label": "Uygulamalar"
}
}
},
@@ -15,7 +15,7 @@ description: 以代码的形式构建并管理 Twenty 自定义项。
* 以代码定义自定义对象和字段(受管理的数据模型)
* 构建带有自定义触发器的逻辑函数
* Define skills and agents for AI
* 为 AI 定义技能和代理
* 将同一个应用部署到多个工作空间
## 先决条件
@@ -39,10 +39,10 @@ yarn twenty app:dev
脚手架工具支持两种模式,用于控制包含哪些示例文件:
```bash filename="Terminal"
# Default (exhaustive): all examples (object, field, logic function, front component, view, navigation menu item, skill, agent)
# 默认(完整):所有示例(对象、字段、逻辑函数、前端组件、视图、导航菜单项、技能、代理)
npx create-twenty-app@latest my-app
# Minimal: only core files (application-config.ts and default-role.ts)
# 最小化:仅核心文件(application-config.ts default-role.ts
npx create-twenty-app@latest my-app --minimal
```
@@ -96,29 +96,29 @@ my-twenty-app/
.oxlintrc.json
tsconfig.json
README.md
public/ # Public assets folder (images, fonts, etc.)
public/ # 公共资源文件夹(图片、字体等)
src/
├── application-config.ts # Required - main application configuration
├── application-config.ts # 必需 - 主应用配置
├── roles/
│ └── default-role.ts # Default role for logic functions
│ └── default-role.ts # 逻辑函数的默认角色
├── objects/
│ └── example-object.ts # Example custom object definition
│ └── example-object.ts # 示例自定义对象定义
├── fields/
│ └── example-field.ts # Example standalone field definition
│ └── example-field.ts # 示例独立字段定义
├── logic-functions/
│ ├── hello-world.ts # Example logic function
│ ├── pre-install.ts # Pre-install logic function
│ └── post-install.ts # Post-install logic function
│ ├── hello-world.ts # 示例逻辑函数
│ ├── pre-install.ts # 安装前逻辑函数
│ └── post-install.ts # 安装后逻辑函数
├── front-components/
│ └── hello-world.tsx # Example front component
│ └── hello-world.tsx # 示例前端组件
├── views/
│ └── example-view.ts # Example saved view definition
│ └── example-view.ts # 示例已保存视图定义
├── navigation-menu-items/
│ └── example-navigation-menu-item.ts # Example sidebar navigation link
│ └── example-navigation-menu-item.ts # 示例侧边栏导航链接
├── skills/
│ └── example-skill.ts # Example AI agent skill definition
│ └── example-skill.ts # 示例 AI 代理技能定义
└── agents/
└── example-agent.ts # Example AI agent definition
└── example-agent.ts # 示例 AI 代理定义
```
使用 `--minimal` 时,只会创建核心文件(`application-config.ts`、`roles/default-role.ts`、`logic-functions/pre-install.ts` 和 `logic-functions/post-install.ts`)。
@@ -150,7 +150,7 @@ my-twenty-app/
| `defineView()` | Saved view definitions |
| `defineNavigationMenuItem()` | Navigation menu item definitions |
| `defineSkill()` | AI agent skill definitions |
| `defineAgent()` | AI agent definitions |
| `defineAgent()` | AI 代理定义 |
<Note>
**文件命名是灵活的。** 实体检测基于 AST — SDK 会扫描你的源文件以查找 `export default define<Entity>({...})` 模式。 你可以按照自己的喜好组织文件和文件夹。 按实体类型分组(例如 `logic-functions/`、`roles/`)只是代码组织的一种约定,并非必需。
@@ -171,7 +171,7 @@ export default defineObject({
后续命令将添加更多文件和文件夹:
* `yarn twenty app:dev` 会在 `node_modules/twenty-sdk/generated` 中自动生成两个类型化 API 客户端:`CoreApiClient`(通过 `/graphql` 获取工作区数据)和 `MetadataApiClient`(通过 `/metadata` 处理工作区配置和文件上传)。
* `yarn twenty app:dev` 会在 `node_modules/twenty-sdk/clients` 中自动生成两个类型化 API 客户端:`CoreApiClient`(通过 `/graphql` 获取工作区数据)和 `MetadataApiClient`(通过 `/metadata` 处理工作区配置和文件上传)。
* `yarn twenty entity:add` will add entity definition files under `src/` for your custom objects, functions, front components, roles, skills, and more.
## 身份验证
@@ -215,20 +215,20 @@ twenty-sdk 提供你在应用中使用的类型化构件和辅助函数。 以
该 SDK 提供辅助函数用于定义你的应用实体。 如 [实体检测](#entity-detection) 中所述,你必须使用 `export default define<Entity>({...})` 才能让你的实体被检测到:
| 函数 | 目的 |
| ---------------------------------- | ------------------------------------ |
| `defineApplication()` | 配置应用元数据(必需,每个应用一个) |
| `defineObject()` | 定义带字段的自定义对象 |
| `defineLogicFunction()` | 定义带处理程序的逻辑函数 |
| `definePreInstallLogicFunction()` | 定义一个安装前逻辑函数(每个应用一个) |
| `definePostInstallLogicFunction()` | 定义一个安装后逻辑函数(每个应用一个) |
| `defineFrontComponent()` | 为自定义 UI 定义前端组件 |
| `defineRole()` | 配置角色权限和对象访问 |
| `defineField()` | 为现有对象扩展额外字段 |
| `defineView()` | Define saved views for objects |
| `defineNavigationMenuItem()` | Define sidebar navigation links |
| `defineSkill()` | Define AI agent skills |
| `defineAgent()` | Define AI agents with system prompts |
| 函数 | 目的 |
| ---------------------------------- | ------------------------------- |
| `defineApplication()` | 配置应用元数据(必需,每个应用一个) |
| `defineObject()` | 定义带字段的自定义对象 |
| `defineLogicFunction()` | 定义带处理程序的逻辑函数 |
| `definePreInstallLogicFunction()` | 定义一个安装前逻辑函数(每个应用一个) |
| `definePostInstallLogicFunction()` | 定义一个安装后逻辑函数(每个应用一个) |
| `defineFrontComponent()` | 为自定义 UI 定义前端组件 |
| `defineRole()` | 配置角色权限和对象访问 |
| `defineField()` | 为现有对象扩展额外字段 |
| `defineView()` | Define saved views for objects |
| `defineNavigationMenuItem()` | Define sidebar navigation links |
| `defineSkill()` | Define AI agent skills |
| `defineAgent()` | 使用系统提示词定义 AI 智能体 |
这些函数会在构建时校验你的配置,并提供 IDE 自动补全和类型安全。
@@ -321,6 +321,72 @@ export default defineObject({
但不建议这样做。
</Note>
### Defining fields on existing objects
Use `defineField()` to add custom fields to existing objects — both standard objects (like `company`, `person`, `opportunity`) and custom objects defined by other apps. Each field lives in its own file and references the target object by its `universalIdentifier`.
To reference standard objects, import `STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS` from `twenty-sdk`. This constant provides stable identifiers for all built-in objects and their fields:
```typescript
// src/fields/apollo-total-funding.field.ts
import {
defineField,
FieldType,
STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS,
} from 'twenty-sdk';
export default defineField({
universalIdentifier: 'c90ae72d-4ddf-4f22-882f-eef98c91e40e',
objectUniversalIdentifier:
STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.company.universalIdentifier,
type: FieldType.CURRENCY,
name: 'apolloTotalFunding',
label: 'Total Funding',
description: 'Total funding raised by the company',
icon: 'IconCash',
});
```
关键点:
* `objectUniversalIdentifier` tells Twenty which object to attach the field to. Use `STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.<objectName>.universalIdentifier` for standard objects.
* Each field requires its own stable `universalIdentifier`, a `name`, `type`, `label`, and the target `objectUniversalIdentifier`.
* You can scaffold new fields using `yarn twenty entity:add` and choosing the field option.
* `STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS` is also exported as `STANDARD_OBJECT` for convenience — both refer to the same constant.
Available standard objects include: `attachment`, `blocklist`, `calendarChannel`, `calendarEvent`, `calendarEventParticipant`, `company`, `connectedAccount`, `dashboard`, `favorite`, `favoriteFolder`, `message`, `messageChannel`, `messageParticipant`, `messageThread`, `note`, `noteTarget`, `opportunity`, `person`, `task`, `taskTarget`, `timelineActivity`, `workflow`, `workflowAutomatedTrigger`, `workflowRun`, `workflowVersion`, and `workspaceMember`.
Each standard object also exposes its field identifiers. For example, to reference a specific field on a standard object in role permissions:
```typescript
STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.company.fields.name.universalIdentifier
```
#### Relation fields on existing objects
You can also define relation fields that link existing objects to your custom objects:
```typescript
// src/fields/people-on-call-recording.field.ts
import { defineField, FieldType, RelationType, STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS } from 'twenty-sdk';
import { CALL_RECORDING_OBJECT_UNIVERSAL_IDENTIFIER } from 'src/objects/call-recording';
import { CALL_RECORDING_ON_PERSON_ID } from 'src/fields/call-recording-on-person.field';
export default defineField({
universalIdentifier: '4a2b3c4d-5e6f-7a8b-9c0d-1e2f3a4b5c6d',
objectUniversalIdentifier:
CALL_RECORDING_OBJECT_UNIVERSAL_IDENTIFIER,
type: FieldType.RELATION,
name: 'person',
label: 'Person',
relationTargetObjectMetadataUniversalIdentifier:
STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.person.universalIdentifier,
relationTargetFieldMetadataUniversalIdentifier:
CALL_RECORDING_ON_PERSON_ID,
relationType: RelationType.MANY_TO_ONE,
});
```
### 应用配置(application-config.ts
每个应用都有一个 `application-config.ts` 文件,用于描述:
@@ -434,7 +500,7 @@ export default defineRole({
// src/app/createPostCard.logic-function.ts
import { defineLogicFunction } from 'twenty-sdk';
import type { DatabaseEventPayload, ObjectRecordCreateEvent, CronPayload, RoutePayload } from 'twenty-sdk';
import { CoreApiClient, type Person } from 'twenty-sdk/generated';
import { CoreApiClient, type Person } from 'twenty-sdk/clients';
const handler = async (params: RoutePayload) => {
const client = new CoreApiClient();
@@ -679,7 +745,7 @@ const handler = async (event: RoutePayload) => {
```typescript
// src/logic-functions/enrich-company.logic-function.ts
import { defineLogicFunction } from 'twenty-sdk';
import { CoreApiClient } from 'twenty-sdk/generated';
import { CoreApiClient } from 'twenty-sdk/clients';
const handler = async (params: { companyName: string; domain?: string }) => {
const client = new CoreApiClient();
@@ -808,7 +874,7 @@ You can create new skills in two ways:
### 代理
Agents define AI agents with system prompts that can operate within your workspace. Use `defineAgent()` to define agents with built-in validation:
Agents 通过系统提示词定义可在你的工作区内运行的 AI 智能体。 使用 `defineAgent()` 以内置校验定义智能体:
```typescript
// src/agents/example-agent.ts
@@ -830,26 +896,27 @@ export default defineAgent({
关键点:
* `name` is a unique identifier string for the agent (kebab-case recommended).
* `label` is the human-readable display name shown in the UI.
* `prompt` contains the system prompt — this is the instruction text that defines the agent's behavior.
* `icon` (optional) sets the icon displayed in the UI.
* `description` (optional) provides additional context about the agent's purpose.
* `name` 是该智能体的唯一标识字符串(推荐使用 kebab-case)。
* `label` 是在 UI 中显示的人类可读名称。
* `prompt` 包含系统提示词—这是定义智能体行为的指令文本。
* `icon`(可选)设置在 UI 中显示的图标。
* `description`(可选)提供有关智能体用途的更多上下文。
You can create new agents in two ways:
你可以通过两种方式创建新智能体:
* **Scaffolded**: Run `yarn twenty entity:add` and choose the option to add a new agent.
* **Manual**: Create a new file and use `defineAgent()`, following the same pattern.
* **脚手架生成**:运行 `yarn twenty entity:add` 并选择添加新智能体的选项。
* **手动**:创建一个新文件,并使用 `defineAgent()`,遵循相同的模式。
### 生成的类型化客户端
两个类型化客户端由 `yarn twenty app:dev` 自动生成(基于你的工作区架构),并存放在 `node_modules/twenty-sdk/generated`
两个类型化客户端由 `yarn twenty app:dev` 自动生成(基于你的工作区架构),并存放在 `node_modules/twenty-sdk/clients`
* **`CoreApiClient`** — 查询 `/graphql` 端点以获取工作区数据
* **`MetadataApiClient`** — 查询 `/metadata` 端点以获取工作区配置并处理文件上传
```typescript
import { CoreApiClient, MetadataApiClient } from 'twenty-sdk/generated';
import { CoreApiClient } from 'twenty-sdk/clients';
import { MetadataApiClient } from 'twenty-sdk/clients';
const client = new CoreApiClient();
const { me } = await client.query({ me: { id: true, displayName: true } });
@@ -858,7 +925,7 @@ const metadataClient = new MetadataApiClient();
const { currentWorkspace } = await metadataClient.query({ currentWorkspace: { id: true } });
```
每当你的对象或字段发生变化时,`yarn twenty app:dev` 都会自动重新生成这两个客户端
每当你的对象或字段发生变化时,`yarn twenty app:dev` 都会自动重新生成 `CoreApiClient`。 `MetadataApiClient` 随 SDK 一并提供,已预构建
#### 逻辑函数中的运行时凭据
@@ -875,10 +942,10 @@ const { currentWorkspace } = await metadataClient.query({ currentWorkspace: { id
#### 上传文件
生成的 `MetadataApiClient` 包含一个 `uploadFile` 方法,用于将文件附加到你的工作区对象的文件类型字段。 由于标准 GraphQL 客户端不原生支持多部分文件上传,该客户端提供了一个专用方法,在底层实现了 [GraphQL 多部分请求规范](https://github.com/jaydenseric/graphql-multipart-request-spec)。
`MetadataApiClient` 包含一个 `uploadFile` 方法,用于将文件附加到你的工作区对象的文件类型字段。 由于标准 GraphQL 客户端不原生支持多部分文件上传,该客户端提供了一个专用方法,在底层实现了 [GraphQL 多部分请求规范](https://github.com/jaydenseric/graphql-multipart-request-spec)。
```typescript
import { MetadataApiClient } from 'twenty-sdk/generated';
import { MetadataApiClient } from 'twenty-sdk/clients';
import * as fs from 'fs';
const metadataClient = new MetadataApiClient();
+2 -2
View File
@@ -149,8 +149,8 @@
"extend": {
"label": "扩展",
"groups": {
"extendCapabilities": {
"label": "功能"
"apps": {
"label": "应用"
}
}
},