@things-factory/ai-assistant 10.1.176 → 10.1.178

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -47,7 +47,8 @@ export declare class ChatMessage {
47
47
  * 로 parse 된 객체. UI 의 fold-able 박스 ("AI 가 이런 도구를 사용했습니다") 가
48
48
  * 페이지 reload / loadHistory 후에도 살아있도록 영속.
49
49
  *
50
- * 형태: ToolUsage[] (assistant.ts 의 시간순 trace, summarizeToolResult 로 압축).
50
+ * 형태: ToolUsage[] (시간순 trace). result 는 값이 아니라 모양(resultShapeOf — 크기 · 건수 · 키 이름 · 오류 코드,
51
+ * ADR-0061 결정 8). 급여 · 지분 값이 대화 행 · 백업 · 내보내기로 복제되지 않는다.
51
52
  * null 이면 도구 호출 없었던 메시지 (text-only 응답).
52
53
  */
53
54
  toolUsages?: string;
@@ -1 +1 @@
1
- {"version":3,"file":"chat-message.js","sourceRoot":"","sources":["../../../server/service/chat-message/chat-message.ts"],"names":[],"mappings":";;;;AAAA;;;;;;;GAOG;AACH,qCAUgB;AAChB,+CAAoD;AACpD,qDAA6C;AAE7C,yDAAgD;AAChD,6CAA4C;AAE5C,qEAA6D;AAE7D,MAAM,SAAS,GAAG,YAAM,CAAC,GAAG,CAAC,WAAW,EAAE,EAAE,CAAC,CAAA;AAC7C,MAAM,aAAa,GAAG,SAAS,CAAC,IAAI,CAAA;AAK7B,IAAM,WAAW,GAAjB,MAAM,WAAW;IAyGtB,oCAAoC;IACpC,IAKI,cAAc;QAChB,IAAI,CAAC,IAAI,CAAC,UAAU;YAAE,OAAO,IAAI,CAAA;QACjC,IAAI,CAAC;YACH,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,UAAU,CAAC,CAAA;QACpC,CAAC;QAAC,MAAM,CAAC;YACP,OAAO,IAAI,CAAA;QACb,CAAC;IACH,CAAC;IAwBD,IACI,aAAa;QACf,IAAI,CAAC,IAAI,CAAC,SAAS;YAAE,OAAO,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E,EAAE,QAAQ,EAAE,IAAI,EAAE,QAAQ,EAAE,UAAU,EAAE,CAAC;sCACzD,WAAW;kDAAA;AAQ3B;IANC,IAAA,oBAAU,EAAC,CAAC,OAAoB,EAAE,EAAE,CAAC,OAAO,CAAC,aAAa,CAAC;IAC3D,IAAA,oBAAK,EAAC;QACL,QAAQ,EAAE,IAAI;QACd,WAAW,EACT,yGAAyG;KAC5G,CAAC;;oDACsB;AAIxB;IAFC,IAAA,0BAAgB,GAAE;IAClB,IAAA,oBAAK,EAAC,EAAE,QAAQ,EAAE,IAAI,EAAE,WAAW,EAAE,qBAAqB,EAAE,CAAC;sCAClD,IAAI;8CAAA;AAIhB;IAFC,IAAA,0BAAgB,GAAE;IAClB,IAAA,oBAAK,EAAC,EAAE,QAAQ,EAAE,IAAI,EAAE,WAAW,EAAE,qEAAqE,EAAE,CAAC;sCAClG,IAAI;8CAAA;AAIhB;IAFC,IAAA,0BAAgB,GAAE;IAClB,IAAA,oBAAK,EAAC,EAAE,QAAQ,EAAE,IAAI,EAAE,WAAW,EAAE,wBAAwB,EAAE,CAAC;sCACrD,IAAI;8CAAA;sBA7PL,WAAW;IAHvB,IAAA,gBAAM,GAAE;IACR,IAAA,eAAK,EAAC,mBAAmB,EAAE,CAAC,OAAoB,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,OAAO,EAAE,OAAO,CAAC,SAAS,CAAC,CAAC;IAC1F,IAAA,yBAAU,EAAC,EAAE,WAAW,EAAE,yCAAyC,EAAE,CAAC;GAC1D,WAAW,CA8PvB","sourcesContent":["/**\n * ChatMessage — ChatSession 의 한 메시지.\n *\n * role: 'user' | 'assistant' | 'system'\n * 'system' 은 사용자 직접 편집/import 진행 등 시스템이 자동 생성하는 컨텍스트 메시지.\n *\n * relatedPatchId / relatedImportSessionId 로 메시지가 트리거한 패치·임포트와 연결.\n */\nimport {\n Column,\n CreateDateColumn,\n DeleteDateColumn,\n Entity,\n Index,\n ManyToOne,\n PrimaryGeneratedColumn,\n RelationId,\n UpdateDateColumn\n} from 'typeorm'\nimport { Field, ID, ObjectType } from 'type-graphql'\nimport { GraphQLJSON } from 'graphql-scalars'\n\nimport { User } from '@things-factory/auth-base'\nimport { config } from '@things-factory/env'\n\nimport { ChatSession } from '../chat-session/chat-session.js'\n\nconst ORMCONFIG = config.get('ormconfig', {})\nconst DATABASE_TYPE = ORMCONFIG.type\n\n@Entity()\n@Index('ix_chat_message_1', (message: ChatMessage) => [message.session, message.createdAt])\n@ObjectType({ description: 'A single chat message in a ChatSession.' })\nexport class ChatMessage {\n @PrimaryGeneratedColumn('uuid')\n @Field(type => ID, { nullable: true })\n readonly id?: string\n\n @ManyToOne(type => ChatSession, session => session.messages, { onDelete: 'CASCADE' })\n session?: ChatSession\n\n @RelationId((message: ChatMessage) => message.session)\n sessionId?: string\n\n @Column({ type: 'varchar', length: 16 })\n @Field({ description: \"'user' | 'assistant' | 'system'\" })\n role!: string\n\n @Column({\n type:\n DATABASE_TYPE == 'mysql' || DATABASE_TYPE == 'mariadb'\n ? 'longtext'\n : DATABASE_TYPE == 'oracle'\n ? 'clob'\n : DATABASE_TYPE == 'mssql'\n ? 'nvarchar'\n : 'text',\n length: DATABASE_TYPE == 'mssql' ? 'MAX' : undefined\n })\n @Field({ description: 'Message content' })\n content!: string\n\n /**\n * 이 말이 누구에게 한 말인가 — `'assistant'` · `'room'`(ADR-0070 A15 결정 ①).\n *\n * **값은 그 행을 쓴 문이 찍는다.** 어시스턴트에게 묻는 문(`assistantChat`)이 저장한 사람의 행은\n * `assistant` 이고, 사람끼리의 문(`appendSessionTurns`)이 저장한 행은 `room` 이다. 클라이언트가\n * 인자로 보내지 않는다 — 인자로 받으면 「어느 문을 불렀나」와 「무엇을 적어 보냈나」 두 사실이\n * 생기고, 둘은 어긋날 수 있다.\n *\n * 사람의 행에만 뜻이 있다. 어시스턴트의 답은 `parentMessage` 로 자기를 부른 턴에 귀속되고,\n * `system` 행은 누구에게 한 말이 아니다.\n */\n @Column({ type: 'varchar', length: 16, nullable: true })\n @Field({ nullable: true, description: \"Who this turn was for: 'assistant' | 'room'. Written by the door that stored it, never sent by the client.\" })\n addressee?: string\n\n /**\n * 이 행의 값이 지나온 문들 — ADR-0073 판정 1.\n *\n * 어시스턴트의 답과 제안 행에만 채워진다. 사람의 말은 빈 목록이다 — 사람이 자기 입으로 한 말에는\n * 문이 없다. 답을 저장할 때 그 턴에 부른 도구들의 `doors`(ADR-0072)를 합쳐 옮겨 적는다.\n *\n * 읽을 때마다 **읽는 사람**이 이 문을 전부 지나는지 보고, 못 지나면 본문 대신 한 줄이 나간다. 그래서\n * 이 칸은 \"누가 볼 수 있나\"를 적은 것이고, 저장된 값 자체는 누구에게도 달라지지 않는다.\n *\n * 목록이 비면 누구나 읽는다. 등록기가 모르는 도구가 답에 끼면 `unresolved:<도구>` 가 적히고 아무도\n * 못 지난다 — 모르는 값은 가려지는 쪽으로 넘어뜨린다.\n */\n @Column({ type: 'simple-array', nullable: true })\n @Field(() => [String], {\n nullable: true,\n description:\n 'GraphQL doors the tools behind this answer went through. Empty for what people typed. A reader who does not pass all of them gets a one-line notice in place of the content.'\n })\n doors?: string[]\n\n /**\n * 이 행이 **이 사람에게** 가려져 나갔는가 — 저장하지 않는다.\n *\n * 같은 행이 사람마다 다르게 나가므로 칸에 적을 값이 없다. 읽어 나갈 때 채운다. 화면은 이것으로\n * 자물쇠를 그리고, 본문에 온 한 줄을 어시스턴트의 말로 오해하지 않는다.\n */\n @Field({ nullable: true, description: 'True when the content was replaced because this reader does not pass the row doors.' })\n redacted?: boolean\n\n @Column({ nullable: true })\n @Field({ nullable: true, description: 'PatchEntry.id this message triggered (if any).' })\n relatedPatchId?: string\n\n @Column({ nullable: true })\n @Field({ nullable: true, description: 'ImportSession.id this message triggered (if any).' })\n relatedImportSessionId?: string\n\n /**\n * AI 가 응답을 만드는 동안 호출한 도구 trace — JSON-stringified.\n *\n * 컬럼은 string (PatchEntry.ops 와 동일 패턴), GraphQL 노출은 toolUsagesJson getter\n * 로 parse 된 객체. UI 의 fold-able 박스 (\"AI 가 이런 도구를 사용했습니다\") 가\n * 페이지 reload / loadHistory 후에도 살아있도록 영속.\n *\n * 형태: ToolUsage[] (assistant.ts 의 시간순 trace, summarizeToolResult 로 압축).\n * null 이면 도구 호출 없었던 메시지 (text-only 응답).\n */\n @Column({\n type:\n DATABASE_TYPE == 'mysql' || DATABASE_TYPE == 'mariadb'\n ? 'longtext'\n : DATABASE_TYPE == 'oracle'\n ? 'clob'\n : DATABASE_TYPE == 'mssql'\n ? 'nvarchar'\n : 'text',\n length: DATABASE_TYPE == 'mssql' ? 'MAX' : undefined,\n nullable: true\n })\n toolUsages?: string\n\n /** GraphQL 노출용 — JSON 배열로 parse. */\n @Field(() => GraphQLJSON, {\n nullable: true,\n description:\n 'Tool usage trace — array of {name, arguments, result, kind}. Only on assistant messages.'\n })\n get toolUsagesJson(): any {\n if (!this.toolUsages) return null\n try {\n return JSON.parse(this.toolUsages)\n } catch {\n return null\n }\n }\n\n /**\n * The proposals this answer made - JSON-stringified, like `toolUsages` (ADR-0097 Q-D4 ④).\n *\n * A card lived only in the mutation's answer, so a refresh took it away, and with it the one place the\n * person could see that a proposal was requested and never answered. Stored, the card comes back with\n * its state read from the conversation's rows. Cleared with the body when the row is redacted\n * (`message-doors.ts` VALUE_CARRYING) - a proposal carries the same values as the answer.\n */\n @Column({\n type:\n DATABASE_TYPE == 'mysql' || DATABASE_TYPE == 'mariadb'\n ? 'longtext'\n : DATABASE_TYPE == 'oracle'\n ? 'clob'\n : DATABASE_TYPE == 'mssql'\n ? 'nvarchar'\n : 'text',\n length: DATABASE_TYPE == 'mssql' ? 'MAX' : undefined,\n nullable: true\n })\n proposals?: string\n\n @Field(() => GraphQLJSON, { nullable: true, description: 'Proposals this answer made - the cards the panel draws. Only on assistant messages.' })\n get proposalsJson(): any {\n if (!this.proposals) return null\n try {\n return JSON.parse(this.proposals)\n } catch {\n return null\n }\n }\n\n /**\n * 접지 경고 — 이 답이 언급했으나 근거(프롬프트·보드 문맥·이력·도구 결과)에 없던 식별자 목록.\n *\n * **왜 영속하는가**: 도크의 협의는 여러 사람이 며칠에 걸쳐 읽는다. 경고가 그 자리에서만\n * 보이고 새로 고치면 사라지면, 나중에 읽는 사람은 검증되지 않은 문장을 검증된 것으로 읽는다.\n * 다시 계산할 수도 없다 — 근거였던 도구 결과 원문은 남지 않고 압축본만 남기 때문이다.\n *\n * 형태: string[] 를 JSON-stringify. 비었으면 null(= 접지 정상).\n */\n /**\n * The files sent with this turn - `[{ id, name, mimetype, size }]` as JSON (design/ai/shared-dock.md §9-2).\n * The files themselves live in attachment-base under the conversation and are opened only through it.\n */\n @Column({ type: 'text', nullable: true })\n attachments?: string\n\n @Field(() => GraphQLJSON, { nullable: true, description: 'Files sent with this turn: [{ id, name, mimetype, size }].' })\n get attachmentsJson(): any {\n if (!this.attachments) return null\n try {\n return JSON.parse(this.attachments)\n } catch {\n return null\n }\n }\n\n @Column({ type: 'varchar', length: 1024, nullable: true })\n groundingWarnings?: string\n\n /** GraphQL 노출용 — 식별자 배열로 parse. */\n @Field(() => GraphQLJSON, {\n nullable: true,\n description: 'Ungrounded identifiers mentioned by this reply (hallucination candidates). Null when grounded.'\n })\n get groundingWarningsJson(): any {\n if (!this.groundingWarnings) return null\n try {\n return JSON.parse(this.groundingWarnings)\n } catch {\n return null\n }\n }\n\n /**\n * 메시지를 일으킨 사용자.\n * - role='user' → 보낸 사용자\n * - role='assistant' → 그 응답을 트리거한 사용자 (직전 user 메시지의 작성자)\n * - role='system' → 시스템 액션을 일으킨 사용자 (예: 직접 편집한 사용자)\n *\n * nullable — legacy 메시지 (이 필드 추가 이전에 작성) 는 null. 또한 ad-hoc 모드 / 시스템\n * 자동 메시지 중 사용자 컨텍스트가 없는 경우도 null 가능.\n */\n @ManyToOne(type => User, { nullable: true })\n @Field(type => User, { nullable: true, description: 'User who triggered this message.' })\n creator?: User\n\n @RelationId((message: ChatMessage) => message.creator)\n creatorId?: string\n\n @ManyToOne(type => User, { nullable: true })\n @Field(type => User, { nullable: true, description: 'Last user to update this message (for future edit support).' })\n updater?: User\n\n @RelationId((message: ChatMessage) => message.updater)\n updaterId?: string\n\n /**\n * 부모 메시지 — 이 메시지가 \"응답하는 대상\" / \"이어가는 메시지\" 의 id.\n *\n * 의미 (role 별):\n * - 'user' → 직전 in-session 메시지 (보통 assistant 또는 system). 첫 turn 은 null.\n * - 'assistant' → 이 응답이 답하는 user 메시지. (regenerate 로 같은 user 메시지를 부모로\n * 하는 형제 assistant 메시지가 생기면 자연스럽게 branching tree 가 됨)\n * - 'system' → 직전 in-session 메시지 (timeline 연속성 유지).\n *\n * 이 한 컬럼으로 향후 어떤 흐름이든 표현 가능 — linear chain / branching (regenerate) /\n * tree (replies-to-specific-message) 등. UI/쿼리는 점진 도입.\n *\n * onDelete: 'SET NULL' — 부모 메시지가 삭제돼도 child 는 남되 dangling 마킹.\n */\n @ManyToOne(type => ChatMessage, { nullable: true, onDelete: 'SET NULL' })\n parentMessage?: ChatMessage\n\n @RelationId((message: ChatMessage) => message.parentMessage)\n @Field({\n nullable: true,\n description:\n 'Id of the message this one is in-response-to / continues. Enables linear / branching / tree structures.'\n })\n parentMessageId?: string\n\n @CreateDateColumn()\n @Field({ nullable: true, description: 'Creation timestamp.' })\n createdAt?: Date\n\n @UpdateDateColumn()\n @Field({ nullable: true, description: 'Last update timestamp (relevant once message editing is supported).' })\n updatedAt?: Date\n\n @DeleteDateColumn()\n @Field({ nullable: true, description: 'Soft delete timestamp.' })\n deletedAt?: Date\n}\n"]}
1
+ {"version":3,"file":"chat-message.js","sourceRoot":"","sources":["../../../server/service/chat-message/chat-message.ts"],"names":[],"mappings":";;;;AAAA;;;;;;;GAOG;AACH,qCAUgB;AAChB,+CAAoD;AACpD,qDAA6C;AAE7C,yDAAgD;AAChD,6CAA4C;AAE5C,qEAA6D;AAE7D,MAAM,SAAS,GAAG,YAAM,CAAC,GAAG,CAAC,WAAW,EAAE,EAAE,CAAC,CAA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C,OAAO,EAAE,OAAO,CAAC,SAAS,CAAC,CAAC;IAC1F,IAAA,yBAAU,EAAC,EAAE,WAAW,EAAE,yCAAyC,EAAE,CAAC;GAC1D,WAAW,CA+PvB","sourcesContent":["/**\n * ChatMessage — ChatSession 의 한 메시지.\n *\n * role: 'user' | 'assistant' | 'system'\n * 'system' 은 사용자 직접 편집/import 진행 등 시스템이 자동 생성하는 컨텍스트 메시지.\n *\n * relatedPatchId / relatedImportSessionId 로 메시지가 트리거한 패치·임포트와 연결.\n */\nimport {\n Column,\n CreateDateColumn,\n DeleteDateColumn,\n Entity,\n Index,\n ManyToOne,\n PrimaryGeneratedColumn,\n RelationId,\n UpdateDateColumn\n} from 'typeorm'\nimport { Field, ID, ObjectType } from 'type-graphql'\nimport { GraphQLJSON } from 'graphql-scalars'\n\nimport { User } from '@things-factory/auth-base'\nimport { config } from '@things-factory/env'\n\nimport { ChatSession } from '../chat-session/chat-session.js'\n\nconst ORMCONFIG = config.get('ormconfig', {})\nconst DATABASE_TYPE = ORMCONFIG.type\n\n@Entity()\n@Index('ix_chat_message_1', (message: ChatMessage) => [message.session, message.createdAt])\n@ObjectType({ description: 'A single chat message in a ChatSession.' })\nexport class ChatMessage {\n @PrimaryGeneratedColumn('uuid')\n @Field(type => ID, { nullable: true })\n readonly id?: string\n\n @ManyToOne(type => ChatSession, session => session.messages, { onDelete: 'CASCADE' })\n session?: ChatSession\n\n @RelationId((message: ChatMessage) => message.session)\n sessionId?: string\n\n @Column({ type: 'varchar', length: 16 })\n @Field({ description: \"'user' | 'assistant' | 'system'\" })\n role!: string\n\n @Column({\n type:\n DATABASE_TYPE == 'mysql' || DATABASE_TYPE == 'mariadb'\n ? 'longtext'\n : DATABASE_TYPE == 'oracle'\n ? 'clob'\n : DATABASE_TYPE == 'mssql'\n ? 'nvarchar'\n : 'text',\n length: DATABASE_TYPE == 'mssql' ? 'MAX' : undefined\n })\n @Field({ description: 'Message content' })\n content!: string\n\n /**\n * 이 말이 누구에게 한 말인가 — `'assistant'` · `'room'`(ADR-0070 A15 결정 ①).\n *\n * **값은 그 행을 쓴 문이 찍는다.** 어시스턴트에게 묻는 문(`assistantChat`)이 저장한 사람의 행은\n * `assistant` 이고, 사람끼리의 문(`appendSessionTurns`)이 저장한 행은 `room` 이다. 클라이언트가\n * 인자로 보내지 않는다 — 인자로 받으면 「어느 문을 불렀나」와 「무엇을 적어 보냈나」 두 사실이\n * 생기고, 둘은 어긋날 수 있다.\n *\n * 사람의 행에만 뜻이 있다. 어시스턴트의 답은 `parentMessage` 로 자기를 부른 턴에 귀속되고,\n * `system` 행은 누구에게 한 말이 아니다.\n */\n @Column({ type: 'varchar', length: 16, nullable: true })\n @Field({ nullable: true, description: \"Who this turn was for: 'assistant' | 'room'. Written by the door that stored it, never sent by the client.\" })\n addressee?: string\n\n /**\n * 이 행의 값이 지나온 문들 — ADR-0073 판정 1.\n *\n * 어시스턴트의 답과 제안 행에만 채워진다. 사람의 말은 빈 목록이다 — 사람이 자기 입으로 한 말에는\n * 문이 없다. 답을 저장할 때 그 턴에 부른 도구들의 `doors`(ADR-0072)를 합쳐 옮겨 적는다.\n *\n * 읽을 때마다 **읽는 사람**이 이 문을 전부 지나는지 보고, 못 지나면 본문 대신 한 줄이 나간다. 그래서\n * 이 칸은 \"누가 볼 수 있나\"를 적은 것이고, 저장된 값 자체는 누구에게도 달라지지 않는다.\n *\n * 목록이 비면 누구나 읽는다. 등록기가 모르는 도구가 답에 끼면 `unresolved:<도구>` 가 적히고 아무도\n * 못 지난다 — 모르는 값은 가려지는 쪽으로 넘어뜨린다.\n */\n @Column({ type: 'simple-array', nullable: true })\n @Field(() => [String], {\n nullable: true,\n description:\n 'GraphQL doors the tools behind this answer went through. Empty for what people typed. A reader who does not pass all of them gets a one-line notice in place of the content.'\n })\n doors?: string[]\n\n /**\n * 이 행이 **이 사람에게** 가려져 나갔는가 — 저장하지 않는다.\n *\n * 같은 행이 사람마다 다르게 나가므로 칸에 적을 값이 없다. 읽어 나갈 때 채운다. 화면은 이것으로\n * 자물쇠를 그리고, 본문에 온 한 줄을 어시스턴트의 말로 오해하지 않는다.\n */\n @Field({ nullable: true, description: 'True when the content was replaced because this reader does not pass the row doors.' })\n redacted?: boolean\n\n @Column({ nullable: true })\n @Field({ nullable: true, description: 'PatchEntry.id this message triggered (if any).' })\n relatedPatchId?: string\n\n @Column({ nullable: true })\n @Field({ nullable: true, description: 'ImportSession.id this message triggered (if any).' })\n relatedImportSessionId?: string\n\n /**\n * AI 가 응답을 만드는 동안 호출한 도구 trace — JSON-stringified.\n *\n * 컬럼은 string (PatchEntry.ops 와 동일 패턴), GraphQL 노출은 toolUsagesJson getter\n * 로 parse 된 객체. UI 의 fold-able 박스 (\"AI 가 이런 도구를 사용했습니다\") 가\n * 페이지 reload / loadHistory 후에도 살아있도록 영속.\n *\n * 형태: ToolUsage[] (시간순 trace). result 는 값이 아니라 모양(resultShapeOf — 크기 · 건수 · 키 이름 · 오류 코드,\n * ADR-0061 결정 8). 급여 · 지분 값이 대화 행 · 백업 · 내보내기로 복제되지 않는다.\n * null 이면 도구 호출 없었던 메시지 (text-only 응답).\n */\n @Column({\n type:\n DATABASE_TYPE == 'mysql' || DATABASE_TYPE == 'mariadb'\n ? 'longtext'\n : DATABASE_TYPE == 'oracle'\n ? 'clob'\n : DATABASE_TYPE == 'mssql'\n ? 'nvarchar'\n : 'text',\n length: DATABASE_TYPE == 'mssql' ? 'MAX' : undefined,\n nullable: true\n })\n toolUsages?: string\n\n /** GraphQL 노출용 — JSON 배열로 parse. */\n @Field(() => GraphQLJSON, {\n nullable: true,\n description:\n 'Tool usage trace — array of {name, arguments, result, kind}. Only on assistant messages.'\n })\n get toolUsagesJson(): any {\n if (!this.toolUsages) return null\n try {\n return JSON.parse(this.toolUsages)\n } catch {\n return null\n }\n }\n\n /**\n * The proposals this answer made - JSON-stringified, like `toolUsages` (ADR-0097 Q-D4 ④).\n *\n * A card lived only in the mutation's answer, so a refresh took it away, and with it the one place the\n * person could see that a proposal was requested and never answered. Stored, the card comes back with\n * its state read from the conversation's rows. Cleared with the body when the row is redacted\n * (`message-doors.ts` VALUE_CARRYING) - a proposal carries the same values as the answer.\n */\n @Column({\n type:\n DATABASE_TYPE == 'mysql' || DATABASE_TYPE == 'mariadb'\n ? 'longtext'\n : DATABASE_TYPE == 'oracle'\n ? 'clob'\n : DATABASE_TYPE == 'mssql'\n ? 'nvarchar'\n : 'text',\n length: DATABASE_TYPE == 'mssql' ? 'MAX' : undefined,\n nullable: true\n })\n proposals?: string\n\n @Field(() => GraphQLJSON, { nullable: true, description: 'Proposals this answer made - the cards the panel draws. Only on assistant messages.' })\n get proposalsJson(): any {\n if (!this.proposals) return null\n try {\n return JSON.parse(this.proposals)\n } catch {\n return null\n }\n }\n\n /**\n * 접지 경고 — 이 답이 언급했으나 근거(프롬프트·보드 문맥·이력·도구 결과)에 없던 식별자 목록.\n *\n * **왜 영속하는가**: 도크의 협의는 여러 사람이 며칠에 걸쳐 읽는다. 경고가 그 자리에서만\n * 보이고 새로 고치면 사라지면, 나중에 읽는 사람은 검증되지 않은 문장을 검증된 것으로 읽는다.\n * 다시 계산할 수도 없다 — 근거였던 도구 결과 원문은 남지 않고 압축본만 남기 때문이다.\n *\n * 형태: string[] 를 JSON-stringify. 비었으면 null(= 접지 정상).\n */\n /**\n * The files sent with this turn - `[{ id, name, mimetype, size }]` as JSON (design/ai/shared-dock.md §9-2).\n * The files themselves live in attachment-base under the conversation and are opened only through it.\n */\n @Column({ type: 'text', nullable: true })\n attachments?: string\n\n @Field(() => GraphQLJSON, { nullable: true, description: 'Files sent with this turn: [{ id, name, mimetype, size }].' })\n get attachmentsJson(): any {\n if (!this.attachments) return null\n try {\n return JSON.parse(this.attachments)\n } catch {\n return null\n }\n }\n\n @Column({ type: 'varchar', length: 1024, nullable: true })\n groundingWarnings?: string\n\n /** GraphQL 노출용 — 식별자 배열로 parse. */\n @Field(() => GraphQLJSON, {\n nullable: true,\n description: 'Ungrounded identifiers mentioned by this reply (hallucination candidates). Null when grounded.'\n })\n get groundingWarningsJson(): any {\n if (!this.groundingWarnings) return null\n try {\n return JSON.parse(this.groundingWarnings)\n } catch {\n return null\n }\n }\n\n /**\n * 메시지를 일으킨 사용자.\n * - role='user' → 보낸 사용자\n * - role='assistant' → 그 응답을 트리거한 사용자 (직전 user 메시지의 작성자)\n * - role='system' → 시스템 액션을 일으킨 사용자 (예: 직접 편집한 사용자)\n *\n * nullable — legacy 메시지 (이 필드 추가 이전에 작성) 는 null. 또한 ad-hoc 모드 / 시스템\n * 자동 메시지 중 사용자 컨텍스트가 없는 경우도 null 가능.\n */\n @ManyToOne(type => User, { nullable: true })\n @Field(type => User, { nullable: true, description: 'User who triggered this message.' })\n creator?: User\n\n @RelationId((message: ChatMessage) => message.creator)\n creatorId?: string\n\n @ManyToOne(type => User, { nullable: true })\n @Field(type => User, { nullable: true, description: 'Last user to update this message (for future edit support).' })\n updater?: User\n\n @RelationId((message: ChatMessage) => message.updater)\n updaterId?: string\n\n /**\n * 부모 메시지 — 이 메시지가 \"응답하는 대상\" / \"이어가는 메시지\" 의 id.\n *\n * 의미 (role 별):\n * - 'user' → 직전 in-session 메시지 (보통 assistant 또는 system). 첫 turn 은 null.\n * - 'assistant' → 이 응답이 답하는 user 메시지. (regenerate 로 같은 user 메시지를 부모로\n * 하는 형제 assistant 메시지가 생기면 자연스럽게 branching tree 가 됨)\n * - 'system' → 직전 in-session 메시지 (timeline 연속성 유지).\n *\n * 이 한 컬럼으로 향후 어떤 흐름이든 표현 가능 — linear chain / branching (regenerate) /\n * tree (replies-to-specific-message) 등. UI/쿼리는 점진 도입.\n *\n * onDelete: 'SET NULL' — 부모 메시지가 삭제돼도 child 는 남되 dangling 마킹.\n */\n @ManyToOne(type => ChatMessage, { nullable: true, onDelete: 'SET NULL' })\n parentMessage?: ChatMessage\n\n @RelationId((message: ChatMessage) => message.parentMessage)\n @Field({\n nullable: true,\n description:\n 'Id of the message this one is in-response-to / continues. Enables linear / branching / tree structures.'\n })\n parentMessageId?: string\n\n @CreateDateColumn()\n @Field({ nullable: true, description: 'Creation timestamp.' })\n createdAt?: Date\n\n @UpdateDateColumn()\n @Field({ nullable: true, description: 'Last update timestamp (relevant once message editing is supported).' })\n updatedAt?: Date\n\n @DeleteDateColumn()\n @Field({ nullable: true, description: 'Soft delete timestamp.' })\n deletedAt?: Date\n}\n"]}
@@ -82,6 +82,35 @@ export declare const readCategoryName: (key: string) => string;
82
82
  export declare function declareReadTarget(target: ReadTarget): void;
83
83
  export declare function readTargetOf(key: string | undefined): ReadTarget | undefined;
84
84
  export declare function clearReadTargets(): void;
85
+ /** An argument of a detail read - one variable of its query, read with the entry fields' rules. */
86
+ export interface DetailArg {
87
+ name: string;
88
+ type: 'string' | 'integer' | 'number' | 'boolean' | 'date' | 'enum';
89
+ values?: string[];
90
+ description?: string;
91
+ required?: boolean;
92
+ }
93
+ /**
94
+ * A query whose answer is one thing, not a list - a 360's summary, the receivables, a statement (design/ai/read-targets.md
95
+ * §9). The application declares the query with the fields its screen reads; the framework runs it as the person, with
96
+ * the arguments the model set, and hands the answer over as the query returned it. Nothing is summed or cut here: the
97
+ * selection is the projection, and an answer too long to hand over is refused, never cut.
98
+ */
99
+ export interface DetailRead {
100
+ /** `<app>.<thing>` - the tool is named after it. */
101
+ key: string;
102
+ labelKey?: string;
103
+ /** What it answers, for the model. */
104
+ description: string;
105
+ /** One query with one root field. Its variables are the arguments - each declared in `args`. */
106
+ query: string;
107
+ args?: DetailArg[];
108
+ }
109
+ /** Characters of an answer handed to the model - a longer one is refused, and the model narrows it. */
110
+ export declare const MAX_DETAIL_CHARS = 60000;
111
+ export declare const detailToolName: (key: string) => string;
112
+ export declare function declareDetailRead(target: DetailRead): void;
113
+ export declare function detailReadOf(key: string | undefined): DetailRead | undefined;
85
114
  /** The conditions the model set, read by their declared types; a value that does not fit is said, never guessed at. */
86
115
  export declare function readCriteria(target: ReadTarget, args: any): {
87
116
  criteria: Record<string, unknown>;
@@ -1,9 +1,11 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.UNKNOWN_CURRENCY = exports.readCategoryName = exports.screenToolName = exports.queryToolName = exports.READ_PAGE = exports.ROWS_FOR_MODEL = exports.MAX_READ_ROWS = void 0;
3
+ exports.UNKNOWN_CURRENCY = exports.detailToolName = exports.MAX_DETAIL_CHARS = exports.readCategoryName = exports.screenToolName = exports.queryToolName = exports.READ_PAGE = exports.ROWS_FOR_MODEL = exports.MAX_READ_ROWS = void 0;
4
4
  exports.declareReadTarget = declareReadTarget;
5
5
  exports.readTargetOf = readTargetOf;
6
6
  exports.clearReadTargets = clearReadTargets;
7
+ exports.declareDetailRead = declareDetailRead;
8
+ exports.detailReadOf = detailReadOf;
7
9
  exports.readCriteria = readCriteria;
8
10
  exports.filtersOf = filtersOf;
9
11
  exports.rowOf = rowOf;
@@ -24,6 +26,7 @@ exports.screenAddress = screenAddress;
24
26
  * Pure but for the GraphQL runner, which comes in as an argument - the rules are tested without a server.
25
27
  */
26
28
  const entry_target_js_1 = require("../data-entry/entry-target.js");
29
+ const graphql_1 = require("graphql");
27
30
  /** At most this many rows are read - the AI 작업판 table's own limit (workspace-blocks MAX_TABLE_ROWS). */
28
31
  exports.MAX_READ_ROWS = 1000;
29
32
  /** Rows the model is shown; the rest stay on the card. */
@@ -45,7 +48,7 @@ exports.readCategoryName = readCategoryName;
45
48
  function declareReadTarget(target) {
46
49
  if (!/^[a-z0-9-]+\.[a-z0-9-]+$/.test(target.key))
47
50
  throw new Error(`read target key '${target.key}' is not <app>.<record>`);
48
- if (registry.has(target.key))
51
+ if (registry.has(target.key) || details.has(target.key))
49
52
  throw new Error(`read target '${target.key}' is declared twice`);
50
53
  (0, entry_target_js_1.rootFieldOf)(target.query, 'query');
51
54
  if (!target.columns.length)
@@ -80,6 +83,42 @@ function readTargetOf(key) {
80
83
  }
81
84
  function clearReadTargets() {
82
85
  registry.clear();
86
+ details.clear();
87
+ }
88
+ /** Characters of an answer handed to the model - a longer one is refused, and the model narrows it. */
89
+ exports.MAX_DETAIL_CHARS = 60_000;
90
+ const details = new Map();
91
+ const detailToolName = (key) => `read${pascalOf(key)}`;
92
+ exports.detailToolName = detailToolName;
93
+ /** The variables a query declares, and whether each is required (`!`). */
94
+ function variablesOf(document) {
95
+ const operation = (0, graphql_1.parse)(document).definitions.find((one) => one.kind === 'OperationDefinition');
96
+ return (operation?.variableDefinitions ?? []).map((one) => ({ name: one.variable.name.value, required: one.type.kind === 'NonNullType' && !one.defaultValue }));
97
+ }
98
+ function declareDetailRead(target) {
99
+ if (!/^[a-z0-9-]+\.[a-z0-9-]+$/.test(target.key))
100
+ throw new Error(`detail read key '${target.key}' is not <app>.<thing>`);
101
+ if (details.has(target.key) || registry.has(target.key))
102
+ throw new Error(`read target '${target.key}' is declared twice`);
103
+ (0, entry_target_js_1.rootFieldOf)(target.query, 'query');
104
+ const args = target.args ?? [];
105
+ for (const variable of variablesOf(target.query)) {
106
+ const arg = args.find(one => one.name === variable.name);
107
+ if (!arg)
108
+ throw new Error(`detail read '${target.key}' takes $${variable.name}, which is no argument`);
109
+ if (variable.required && !arg.required)
110
+ throw new Error(`detail read '${target.key}': $${variable.name} is required by the query - declare it required`);
111
+ }
112
+ for (const arg of args) {
113
+ if (!variablesOf(target.query).some(one => one.name === arg.name))
114
+ throw new Error(`detail read '${target.key}' declares '${arg.name}', which its query does not take`);
115
+ if (arg.type === 'enum' && !arg.values?.length)
116
+ throw new Error(`argument '${arg.name}' of '${target.key}' lists no values`);
117
+ }
118
+ details.set(target.key, target);
119
+ }
120
+ function detailReadOf(key) {
121
+ return key ? details.get(key) : undefined;
83
122
  }
84
123
  /** The conditions the model set, read by their declared types; a value that does not fit is said, never guessed at. */
85
124
  function readCriteria(target, args) {
@@ -1 +1 @@
1
- {"version":3,"file":"read-target.js","sourceRoot":"","sources":["../../../server/service/data-read/read-target.ts"],"names":[],"mappings":";;;AAqGA,8CAoBC;AAED,oCAEC;AAED,4CAEC;AAG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AAM,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;KAC/D,CAAA;AACH,CAAC","sourcesContent":["/*\n * AI 조회 - an application's list, read through its own query as the person (operato-application/design/ai/read-targets.md).\n *\n * The application declares what it lets the assistant read: its list query, the conditions the model may set and\n * how each becomes one of the query's filters, the columns to show, and the screen that lists the same records.\n * The framework reads the rows through that query with the person's request state - the same @privilege and\n * domain as the screen - counts and sums them itself, and puts a long result on the AI 작업판 as the query returned\n * it. The model is told the count, the sums and a few rows; it never copies a table.\n *\n * Pure but for the GraphQL runner, which comes in as an argument - the rules are tested without a server.\n */\nimport { readFieldValue, rootFieldOf, type EntryField } from '../data-entry/entry-target.js'\nimport type { GraphqlRunner } from '../data-entry/entry-update.js'\n\nexport interface ReadFilter {\n name: string\n operator: string\n value: unknown\n}\n\n/** A condition the model may set - read with the entry fields' rules, turned into the query's filters by the application. */\nexport interface ReadCriterion extends Omit<EntryField, 'required' | 'reference' | 'total'> {\n filter: (value: any) => ReadFilter | ReadFilter[]\n}\n\nexport interface ReadColumn {\n /** The key in the workspace table. */\n name: string\n /** Where the value is in a row - a dotted path into the query's item (`account.name`). Defaults to `name`. */\n path?: string\n type: 'string' | 'number' | 'date'\n labelKey?: string\n /** A number column the server sums. */\n total?: boolean\n /**\n * The column that holds this amount's currency (ISO 4217, `KRW`). Its sums are kept per currency - amounts of two\n * currencies are never added into one number.\n */\n currency?: string\n}\n\nexport interface ReadScreen {\n /** The application's route of the list screen (`cash-transaction-list`). */\n route: string\n /** The conditions the screen takes, as its address's query arguments. A condition left out is said on the card. */\n params: (criteria: Record<string, any>) => Record<string, string | number | undefined>\n /** The conditions `params` carries - the card names the others as not applied on the screen. */\n takes: string[]\n labelKey?: string\n}\n\nexport interface ReadTarget {\n /** `<app>.<record>` - the tools are named after it. */\n key: string\n /** i18n key naming the records (「은행 입출금」). */\n labelKey?: string\n /** What the records are, for the model. */\n description: string\n /**\n * The list query - takes `$filters: [Filter!]`, `$pagination: Pagination` and `$sortings: [Sorting!]`, and\n * `$search: String` when `search` is declared.\n */\n query: string\n /**\n * The list takes ListParam's free-text term, matched by the resolver across its own searchable fields - the\n * condition `text`. Say what it finds in, for the model.\n */\n search?: { description: string }\n criteria: ReadCriterion[]\n /**\n * Filters every read of this list applies - the records it is of (a book's confirmed lines, not its forecasts). Not\n * a condition: the model neither sees nor sets them, so a read can narrow the list but never widen it.\n */\n fixedFilters?: ReadFilter[]\n columns: ReadColumn[]\n rowsOf: (data: any) => { rows: any[]; total: number }\n /** Orders the rows; the query's own order when left out. */\n sortings?: { name: string; desc?: boolean }[]\n screen?: ReadScreen\n}\n\n/** At most this many rows are read - the AI 작업판 table's own limit (workspace-blocks MAX_TABLE_ROWS). */\nexport const MAX_READ_ROWS = 1000\n/** Rows the model is shown; the rest stay on the card. */\nexport const ROWS_FOR_MODEL = 20\n/** A page of the list query. */\nexport const READ_PAGE = 200\n\nconst registry = new Map<string, ReadTarget>()\n\nconst pascalOf = (key: string) =>\n key\n .split(/[^a-zA-Z0-9]+/)\n .filter(Boolean)\n .map(part => part[0].toUpperCase() + part.slice(1))\n .join('')\n\nexport const queryToolName = (key: string) => `query${pascalOf(key)}`\nexport const screenToolName = (key: string) => `open${pascalOf(key)}Screen`\nexport const readCategoryName = (key: string) => `data-read:${key}`\n\nexport function declareReadTarget(target: ReadTarget): void {\n if (!/^[a-z0-9-]+\\.[a-z0-9-]+$/.test(target.key)) throw new Error(`read target key '${target.key}' is not <app>.<record>`)\n if (registry.has(target.key)) throw new Error(`read target '${target.key}' is declared twice`)\n rootFieldOf(target.query, 'query')\n if (!target.columns.length) throw new Error(`read target '${target.key}' shows no column`)\n for (const column of target.columns.filter(one => one.currency)) {\n if (!column.total || column.type !== 'number') throw new Error(`column '${column.name}' of '${target.key}' names a currency but is not a summed number`)\n if (target.columns.find(one => one.name === column.currency)?.type !== 'string') throw new Error(`column '${column.name}' of '${target.key}' takes its currency from '${column.currency}', which is no string column`)\n }\n const names = new Set<string>()\n for (const criterion of target.criteria) {\n if (criterion.name === 'id') throw new Error(`read target '${target.key}' declares 'id' - every target takes it`)\n if (criterion.name === 'text' && target.search) throw new Error(`read target '${target.key}' declares 'text' and search - search is the text condition`)\n if (names.has(criterion.name)) throw new Error(`read target '${target.key}' names the condition '${criterion.name}' twice`)\n names.add(criterion.name)\n if (criterion.type === 'enum' && !criterion.values?.length) throw new Error(`condition '${criterion.name}' of '${target.key}' lists no values`)\n }\n if (target.search) names.add('text')\n for (const taken of target.screen?.takes ?? []) if (!names.has(taken)) throw new Error(`the screen of '${target.key}' takes '${taken}', which is no condition`)\n registry.set(target.key, target)\n}\n\nexport function readTargetOf(key: string | undefined): ReadTarget | undefined {\n return key ? registry.get(key) : undefined\n}\n\nexport function clearReadTargets(): void {\n registry.clear()\n}\n\n/** The conditions the model set, read by their declared types; a value that does not fit is said, never guessed at. */\nexport function readCriteria(target: ReadTarget, args: any): { criteria: Record<string, unknown>; refused: { name: string; code: string }[] } {\n const criteria: Record<string, unknown> = {}\n const refused: { name: string; code: string }[] = []\n /* One record by its id - every target takes it (the id a list answer or a find tool gave). */\n if (typeof args?.id === 'string' && args.id.trim()) criteria.id = args.id.trim()\n if (target.search && typeof args?.text === 'string' && args.text.trim()) criteria.text = args.text.trim()\n for (const criterion of target.criteria) {\n const value = args?.[criterion.name]\n if (value === undefined || value === null || value === '') continue\n const { read, code } = readFieldValue(criterion as EntryField, value)\n if (read === undefined) refused.push({ name: criterion.name, code: code ?? 'unreadable' })\n else criteria[criterion.name] = read\n }\n return { criteria, refused }\n}\n\nexport function filtersOf(target: ReadTarget, criteria: Record<string, unknown>): ReadFilter[] {\n return [\n ...(typeof criteria.id === 'string' ? [{ name: 'id', operator: 'eq', value: criteria.id }] : []),\n ...target.criteria.flatMap(criterion => (criterion.name in criteria ? [criterion.filter(criteria[criterion.name])].flat() : []))\n ]\n}\n\nconst valueAt = (row: any, path: string) => path.split('.').reduce((at, part) => (at === null || at === undefined ? undefined : at[part]), row)\n\n/** One row as the columns say - a number column as a number, a missing value as null. */\nexport function rowOf(target: ReadTarget, item: any): Record<string, string | number | null> {\n return Object.fromEntries([\n /* The id names the record to the model - for one record's detail, a change, or its screen. */\n ...(item?.id ? [['id', String(item.id)] as [string, string]] : []),\n ...target.columns.map(column => {\n const raw = valueAt(item, column.path ?? column.name)\n if (raw === undefined || raw === null || raw === '') return [column.name, null]\n if (column.type === 'number') {\n const number = Number(raw)\n return [column.name, Number.isFinite(number) ? number : null]\n }\n return [column.name, String(raw)]\n })\n ])\n}\n\n/**\n * Reads the rows through the application's query, page by page, up to MAX_READ_ROWS. `complete` is false when the\n * list holds more - a sum of the rows read is then not the sum of the list, and is never said as one.\n */\nexport async function readRows(target: ReadTarget, filters: ReadFilter[], run: GraphqlRunner, search?: string): Promise<{ rows: Record<string, any>[]; total: number; complete: boolean }> {\n const rows: Record<string, any>[] = []\n let total = 0\n for (let page = 1; rows.length < MAX_READ_ROWS; page++) {\n const answer = await run(target.query, {\n filters: [...filters, ...(target.fixedFilters ?? [])],\n ...(search ? { search } : {}),\n pagination: { page, limit: READ_PAGE },\n ...(target.sortings ? { sortings: target.sortings } : {})\n })\n if (answer.errors?.length) throw new Error(answer.errors.map(one => one.message).join('; '))\n const read = target.rowsOf(answer.data)\n total = Number(read?.total) || 0\n const items = read?.rows ?? []\n rows.push(...items.slice(0, MAX_READ_ROWS - rows.length).map(item => rowOf(target, item)))\n if (items.length < READ_PAGE || rows.length >= total) break\n }\n return { rows, total, complete: rows.length >= total }\n}\n\n/** A column's sum - one number, or one per currency when the column names its currency (`{ KRW: 1000, USD: 100 }`). */\nexport type ReadSum = number | Record<string, number>\n\nexport interface ReadGroup {\n key: string\n count: number\n sums: Record<string, ReadSum>\n}\n\n/** The currency a row without one is summed under - said as it is, never taken for the domain's own. */\nexport const UNKNOWN_CURRENCY = 'unknown'\n\nconst sumOf = (rows: Record<string, any>[], name: string) => Math.round(rows.reduce((sum, row) => sum + (typeof row[name] === 'number' ? row[name] : 0), 0) * 100) / 100\n\n/** The sums of the number columns marked total - the server's, never the model's; a column with a currency per currency. */\nexport function sumsOf(target: ReadTarget, rows: Record<string, any>[]): Record<string, ReadSum> {\n const sums: Record<string, ReadSum> = {}\n for (const column of target.columns.filter(one => one.total && one.type === 'number')) {\n if (!column.currency) {\n sums[column.name] = sumOf(rows, column.name)\n continue\n }\n const byCurrency = new Map<string, Record<string, any>[]>()\n for (const row of rows) {\n const code = typeof row[column.currency] === 'string' && row[column.currency] ? row[column.currency] : UNKNOWN_CURRENCY\n byCurrency.set(code, [...(byCurrency.get(code) ?? []), row])\n }\n sums[column.name] = Object.fromEntries([...byCurrency].sort(([a], [b]) => a.localeCompare(b)).map(([code, members]) => [code, sumOf(members, column.name)]))\n }\n return sums\n}\n\n/** The currencies a set of sums holds for one column - none for a column summed as one number. */\nexport function currenciesOf(sums: Record<string, ReadSum>[], column: string): string[] {\n const codes = new Set<string>()\n for (const one of sums) if (one[column] && typeof one[column] === 'object') for (const code of Object.keys(one[column] as object)) codes.add(code)\n return [...codes].sort()\n}\n\n/** The rows grouped by one column - a date column by its month - each with its count and sums, largest first. */\nexport function groupsOf(target: ReadTarget, rows: Record<string, any>[], by: string): ReadGroup[] | undefined {\n const column = target.columns.find(one => one.name === by)\n if (!column) return undefined\n const groups = new Map<string, Record<string, any>[]>()\n for (const row of rows) {\n const value = row[by]\n const key = value === null || value === undefined ? '' : column.type === 'date' ? String(value).slice(0, 7) : String(value)\n groups.set(key, [...(groups.get(key) ?? []), row])\n }\n const list = [...groups].map(([key, members]) => ({ key, count: members.length, sums: sumsOf(target, members) }))\n if (column.type === 'date') return list.sort((a, b) => a.key.localeCompare(b.key))\n /* Largest first by the first sum - in its one currency; groups in two currencies have no common size, so by count. */\n const first = target.columns.find(one => one.total)?.name\n const codes = first ? currenciesOf(list.map(group => group.sums), first) : []\n const size = (group: ReadGroup) => {\n const sum = first ? group.sums[first] : undefined\n return typeof sum === 'number' ? Math.abs(sum) : codes.length === 1 && sum ? Math.abs(sum[codes[0]] ?? 0) : undefined\n }\n return list.sort((a, b) => {\n const [x, y] = [size(a), size(b)]\n return x !== undefined && y !== undefined && codes.length <= 1 ? y - x : b.count - a.count\n })\n}\n\n/** The address of the target's list screen with the conditions it takes, and the conditions it does not. */\nexport function screenAddress(target: ReadTarget, criteria: Record<string, unknown>): { href: string; applied: string[]; notApplied: string[] } | undefined {\n const screen = target.screen\n if (!screen) return undefined\n const params = new URLSearchParams()\n for (const [name, value] of Object.entries(screen.params(criteria))) if (value !== undefined && value !== null && value !== '') params.set(name, String(value))\n const given = Object.keys(criteria)\n const query = params.toString()\n return {\n href: query ? `${screen.route}?${query}` : screen.route,\n applied: given.filter(name => screen.takes.includes(name)),\n notApplied: given.filter(name => !screen.takes.includes(name))\n }\n}\n"]}
1
+ {"version":3,"file":"read-target.js","sourceRoot":"","sources":["../../../server/service/data-read/read-target.ts"],"names":[],"mappings":";;;AAsGA,8CAoBC;AAED,oCAEC;AAED,4CAGC;AA2CD,8CAeC;AAED,oCAEC;AAGD,oCAcC;AAED,8BAKC;AAKD,sBAcC;AAMD,4BAkBC;AAiBD,wBAeC;AAGD,oCAIC;AAGD,4BAsBC;AAGD,sCAYC;AAnVD;;;;;;;;;;GAUG;AACH,mEAA4F;AAE5F,qCAA+B;AAqE/B,wGAAwG;AAC3F,QAAA,aAAa,GAAG,IAAI,CAAA;AACjC,0DAA0D;AAC7C,QAAA,cAAc,GAAG,EAAE,CAAA;AAChC,gCAAgC;AACnB,QAAA,SAAS,GAAG,GAAG,CAAA;AAE5B,MAAM,QAAQ,GAAG,IAAI,GAAG,EAAsB,CAAA;AAE9C,MAAM,QAAQ,GAAG,CAAC,GAAW,EAAE,EAAE,CAC/B,GAAG;KACA,KAAK,CAAC,eAAe,CAAC;KACtB,MAAM,CAAC,OAAO,CAAC;KACf,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC,CA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AA;IAC5B,IAAI,CAAC,MAAM;QAAE,OAAO,SAAS,CAAA;IAC7B,MAAM,MAAM,GAAG,IAAI,eAAe,EAAE,CAAA;IACpC,KAAK,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;QAAE,IAAI,KAAK,KAAK,SAAS,IAAI,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,EAAE;YAAE,MAAM,CAAC,GAAG,CAAC,IAAI,EAAE,MAAM,CAAC,KAAK,CAAC,CAAC,CAAA;IAC/J,MAAM,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAA;IACnC,MAAM,KAAK,GAAG,MAAM,CAAC,QAAQ,EAAE,CAAA;IAC/B,OAAO;QACL,IAAI,EAAE,KAAK,CAAC,CAAC,CAAC,GAAG,MAAM,CAAC,KAAK,IAAI,KAAK,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK;QACvD,OAAO,EAAE,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;QAC1D,UAAU,EAAE,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;KAC/D,CAAA;AACH,CAAC","sourcesContent":["/*\n * AI 조회 - an application's list, read through its own query as the person (operato-application/design/ai/read-targets.md).\n *\n * The application declares what it lets the assistant read: its list query, the conditions the model may set and\n * how each becomes one of the query's filters, the columns to show, and the screen that lists the same records.\n * The framework reads the rows through that query with the person's request state - the same @privilege and\n * domain as the screen - counts and sums them itself, and puts a long result on the AI 작업판 as the query returned\n * it. The model is told the count, the sums and a few rows; it never copies a table.\n *\n * Pure but for the GraphQL runner, which comes in as an argument - the rules are tested without a server.\n */\nimport { readFieldValue, rootFieldOf, type EntryField } from '../data-entry/entry-target.js'\nimport type { GraphqlRunner } from '../data-entry/entry-update.js'\nimport { parse } from 'graphql'\n\nexport interface ReadFilter {\n name: string\n operator: string\n value: unknown\n}\n\n/** A condition the model may set - read with the entry fields' rules, turned into the query's filters by the application. */\nexport interface ReadCriterion extends Omit<EntryField, 'required' | 'reference' | 'total'> {\n filter: (value: any) => ReadFilter | ReadFilter[]\n}\n\nexport interface ReadColumn {\n /** The key in the workspace table. */\n name: string\n /** Where the value is in a row - a dotted path into the query's item (`account.name`). Defaults to `name`. */\n path?: string\n type: 'string' | 'number' | 'date'\n labelKey?: string\n /** A number column the server sums. */\n total?: boolean\n /**\n * The column that holds this amount's currency (ISO 4217, `KRW`). Its sums are kept per currency - amounts of two\n * currencies are never added into one number.\n */\n currency?: string\n}\n\nexport interface ReadScreen {\n /** The application's route of the list screen (`cash-transaction-list`). */\n route: string\n /** The conditions the screen takes, as its address's query arguments. A condition left out is said on the card. */\n params: (criteria: Record<string, any>) => Record<string, string | number | undefined>\n /** The conditions `params` carries - the card names the others as not applied on the screen. */\n takes: string[]\n labelKey?: string\n}\n\nexport interface ReadTarget {\n /** `<app>.<record>` - the tools are named after it. */\n key: string\n /** i18n key naming the records (「은행 입출금」). */\n labelKey?: string\n /** What the records are, for the model. */\n description: string\n /**\n * The list query - takes `$filters: [Filter!]`, `$pagination: Pagination` and `$sortings: [Sorting!]`, and\n * `$search: String` when `search` is declared.\n */\n query: string\n /**\n * The list takes ListParam's free-text term, matched by the resolver across its own searchable fields - the\n * condition `text`. Say what it finds in, for the model.\n */\n search?: { description: string }\n criteria: ReadCriterion[]\n /**\n * Filters every read of this list applies - the records it is of (a book's confirmed lines, not its forecasts). Not\n * a condition: the model neither sees nor sets them, so a read can narrow the list but never widen it.\n */\n fixedFilters?: ReadFilter[]\n columns: ReadColumn[]\n rowsOf: (data: any) => { rows: any[]; total: number }\n /** Orders the rows; the query's own order when left out. */\n sortings?: { name: string; desc?: boolean }[]\n screen?: ReadScreen\n}\n\n/** At most this many rows are read - the AI 작업판 table's own limit (workspace-blocks MAX_TABLE_ROWS). */\nexport const MAX_READ_ROWS = 1000\n/** Rows the model is shown; the rest stay on the card. */\nexport const ROWS_FOR_MODEL = 20\n/** A page of the list query. */\nexport const READ_PAGE = 200\n\nconst registry = new Map<string, ReadTarget>()\n\nconst pascalOf = (key: string) =>\n key\n .split(/[^a-zA-Z0-9]+/)\n .filter(Boolean)\n .map(part => part[0].toUpperCase() + part.slice(1))\n .join('')\n\nexport const queryToolName = (key: string) => `query${pascalOf(key)}`\nexport const screenToolName = (key: string) => `open${pascalOf(key)}Screen`\nexport const readCategoryName = (key: string) => `data-read:${key}`\n\nexport function declareReadTarget(target: ReadTarget): void {\n if (!/^[a-z0-9-]+\\.[a-z0-9-]+$/.test(target.key)) throw new Error(`read target key '${target.key}' is not <app>.<record>`)\n if (registry.has(target.key) || details.has(target.key)) throw new Error(`read target '${target.key}' is declared twice`)\n rootFieldOf(target.query, 'query')\n if (!target.columns.length) throw new Error(`read target '${target.key}' shows no column`)\n for (const column of target.columns.filter(one => one.currency)) {\n if (!column.total || column.type !== 'number') throw new Error(`column '${column.name}' of '${target.key}' names a currency but is not a summed number`)\n if (target.columns.find(one => one.name === column.currency)?.type !== 'string') throw new Error(`column '${column.name}' of '${target.key}' takes its currency from '${column.currency}', which is no string column`)\n }\n const names = new Set<string>()\n for (const criterion of target.criteria) {\n if (criterion.name === 'id') throw new Error(`read target '${target.key}' declares 'id' - every target takes it`)\n if (criterion.name === 'text' && target.search) throw new Error(`read target '${target.key}' declares 'text' and search - search is the text condition`)\n if (names.has(criterion.name)) throw new Error(`read target '${target.key}' names the condition '${criterion.name}' twice`)\n names.add(criterion.name)\n if (criterion.type === 'enum' && !criterion.values?.length) throw new Error(`condition '${criterion.name}' of '${target.key}' lists no values`)\n }\n if (target.search) names.add('text')\n for (const taken of target.screen?.takes ?? []) if (!names.has(taken)) throw new Error(`the screen of '${target.key}' takes '${taken}', which is no condition`)\n registry.set(target.key, target)\n}\n\nexport function readTargetOf(key: string | undefined): ReadTarget | undefined {\n return key ? registry.get(key) : undefined\n}\n\nexport function clearReadTargets(): void {\n registry.clear()\n details.clear()\n}\n\n/* ── One answer of a query ──────────────────────────────────────────────────────────────────────────────────── */\n\n/** An argument of a detail read - one variable of its query, read with the entry fields' rules. */\nexport interface DetailArg {\n name: string\n type: 'string' | 'integer' | 'number' | 'boolean' | 'date' | 'enum'\n values?: string[]\n description?: string\n required?: boolean\n}\n\n/**\n * A query whose answer is one thing, not a list - a 360's summary, the receivables, a statement (design/ai/read-targets.md\n * §9). The application declares the query with the fields its screen reads; the framework runs it as the person, with\n * the arguments the model set, and hands the answer over as the query returned it. Nothing is summed or cut here: the\n * selection is the projection, and an answer too long to hand over is refused, never cut.\n */\nexport interface DetailRead {\n /** `<app>.<thing>` - the tool is named after it. */\n key: string\n labelKey?: string\n /** What it answers, for the model. */\n description: string\n /** One query with one root field. Its variables are the arguments - each declared in `args`. */\n query: string\n args?: DetailArg[]\n}\n\n/** Characters of an answer handed to the model - a longer one is refused, and the model narrows it. */\nexport const MAX_DETAIL_CHARS = 60_000\n\nconst details = new Map<string, DetailRead>()\n\nexport const detailToolName = (key: string) => `read${pascalOf(key)}`\n\n/** The variables a query declares, and whether each is required (`!`). */\nfunction variablesOf(document: string): { name: string; required: boolean }[] {\n const operation: any = parse(document).definitions.find((one: any) => one.kind === 'OperationDefinition')\n return (operation?.variableDefinitions ?? []).map((one: any) => ({ name: one.variable.name.value, required: one.type.kind === 'NonNullType' && !one.defaultValue }))\n}\n\nexport function declareDetailRead(target: DetailRead): void {\n if (!/^[a-z0-9-]+\\.[a-z0-9-]+$/.test(target.key)) throw new Error(`detail read key '${target.key}' is not <app>.<thing>`)\n if (details.has(target.key) || registry.has(target.key)) throw new Error(`read target '${target.key}' is declared twice`)\n rootFieldOf(target.query, 'query')\n const args = target.args ?? []\n for (const variable of variablesOf(target.query)) {\n const arg = args.find(one => one.name === variable.name)\n if (!arg) throw new Error(`detail read '${target.key}' takes $${variable.name}, which is no argument`)\n if (variable.required && !arg.required) throw new Error(`detail read '${target.key}': $${variable.name} is required by the query - declare it required`)\n }\n for (const arg of args) {\n if (!variablesOf(target.query).some(one => one.name === arg.name)) throw new Error(`detail read '${target.key}' declares '${arg.name}', which its query does not take`)\n if (arg.type === 'enum' && !arg.values?.length) throw new Error(`argument '${arg.name}' of '${target.key}' lists no values`)\n }\n details.set(target.key, target)\n}\n\nexport function detailReadOf(key: string | undefined): DetailRead | undefined {\n return key ? details.get(key) : undefined\n}\n\n/** The conditions the model set, read by their declared types; a value that does not fit is said, never guessed at. */\nexport function readCriteria(target: ReadTarget, args: any): { criteria: Record<string, unknown>; refused: { name: string; code: string }[] } {\n const criteria: Record<string, unknown> = {}\n const refused: { name: string; code: string }[] = []\n /* One record by its id - every target takes it (the id a list answer or a find tool gave). */\n if (typeof args?.id === 'string' && args.id.trim()) criteria.id = args.id.trim()\n if (target.search && typeof args?.text === 'string' && args.text.trim()) criteria.text = args.text.trim()\n for (const criterion of target.criteria) {\n const value = args?.[criterion.name]\n if (value === undefined || value === null || value === '') continue\n const { read, code } = readFieldValue(criterion as EntryField, value)\n if (read === undefined) refused.push({ name: criterion.name, code: code ?? 'unreadable' })\n else criteria[criterion.name] = read\n }\n return { criteria, refused }\n}\n\nexport function filtersOf(target: ReadTarget, criteria: Record<string, unknown>): ReadFilter[] {\n return [\n ...(typeof criteria.id === 'string' ? [{ name: 'id', operator: 'eq', value: criteria.id }] : []),\n ...target.criteria.flatMap(criterion => (criterion.name in criteria ? [criterion.filter(criteria[criterion.name])].flat() : []))\n ]\n}\n\nconst valueAt = (row: any, path: string) => path.split('.').reduce((at, part) => (at === null || at === undefined ? undefined : at[part]), row)\n\n/** One row as the columns say - a number column as a number, a missing value as null. */\nexport function rowOf(target: ReadTarget, item: any): Record<string, string | number | null> {\n return Object.fromEntries([\n /* The id names the record to the model - for one record's detail, a change, or its screen. */\n ...(item?.id ? [['id', String(item.id)] as [string, string]] : []),\n ...target.columns.map(column => {\n const raw = valueAt(item, column.path ?? column.name)\n if (raw === undefined || raw === null || raw === '') return [column.name, null]\n if (column.type === 'number') {\n const number = Number(raw)\n return [column.name, Number.isFinite(number) ? number : null]\n }\n return [column.name, String(raw)]\n })\n ])\n}\n\n/**\n * Reads the rows through the application's query, page by page, up to MAX_READ_ROWS. `complete` is false when the\n * list holds more - a sum of the rows read is then not the sum of the list, and is never said as one.\n */\nexport async function readRows(target: ReadTarget, filters: ReadFilter[], run: GraphqlRunner, search?: string): Promise<{ rows: Record<string, any>[]; total: number; complete: boolean }> {\n const rows: Record<string, any>[] = []\n let total = 0\n for (let page = 1; rows.length < MAX_READ_ROWS; page++) {\n const answer = await run(target.query, {\n filters: [...filters, ...(target.fixedFilters ?? [])],\n ...(search ? { search } : {}),\n pagination: { page, limit: READ_PAGE },\n ...(target.sortings ? { sortings: target.sortings } : {})\n })\n if (answer.errors?.length) throw new Error(answer.errors.map(one => one.message).join('; '))\n const read = target.rowsOf(answer.data)\n total = Number(read?.total) || 0\n const items = read?.rows ?? []\n rows.push(...items.slice(0, MAX_READ_ROWS - rows.length).map(item => rowOf(target, item)))\n if (items.length < READ_PAGE || rows.length >= total) break\n }\n return { rows, total, complete: rows.length >= total }\n}\n\n/** A column's sum - one number, or one per currency when the column names its currency (`{ KRW: 1000, USD: 100 }`). */\nexport type ReadSum = number | Record<string, number>\n\nexport interface ReadGroup {\n key: string\n count: number\n sums: Record<string, ReadSum>\n}\n\n/** The currency a row without one is summed under - said as it is, never taken for the domain's own. */\nexport const UNKNOWN_CURRENCY = 'unknown'\n\nconst sumOf = (rows: Record<string, any>[], name: string) => Math.round(rows.reduce((sum, row) => sum + (typeof row[name] === 'number' ? row[name] : 0), 0) * 100) / 100\n\n/** The sums of the number columns marked total - the server's, never the model's; a column with a currency per currency. */\nexport function sumsOf(target: ReadTarget, rows: Record<string, any>[]): Record<string, ReadSum> {\n const sums: Record<string, ReadSum> = {}\n for (const column of target.columns.filter(one => one.total && one.type === 'number')) {\n if (!column.currency) {\n sums[column.name] = sumOf(rows, column.name)\n continue\n }\n const byCurrency = new Map<string, Record<string, any>[]>()\n for (const row of rows) {\n const code = typeof row[column.currency] === 'string' && row[column.currency] ? row[column.currency] : UNKNOWN_CURRENCY\n byCurrency.set(code, [...(byCurrency.get(code) ?? []), row])\n }\n sums[column.name] = Object.fromEntries([...byCurrency].sort(([a], [b]) => a.localeCompare(b)).map(([code, members]) => [code, sumOf(members, column.name)]))\n }\n return sums\n}\n\n/** The currencies a set of sums holds for one column - none for a column summed as one number. */\nexport function currenciesOf(sums: Record<string, ReadSum>[], column: string): string[] {\n const codes = new Set<string>()\n for (const one of sums) if (one[column] && typeof one[column] === 'object') for (const code of Object.keys(one[column] as object)) codes.add(code)\n return [...codes].sort()\n}\n\n/** The rows grouped by one column - a date column by its month - each with its count and sums, largest first. */\nexport function groupsOf(target: ReadTarget, rows: Record<string, any>[], by: string): ReadGroup[] | undefined {\n const column = target.columns.find(one => one.name === by)\n if (!column) return undefined\n const groups = new Map<string, Record<string, any>[]>()\n for (const row of rows) {\n const value = row[by]\n const key = value === null || value === undefined ? '' : column.type === 'date' ? String(value).slice(0, 7) : String(value)\n groups.set(key, [...(groups.get(key) ?? []), row])\n }\n const list = [...groups].map(([key, members]) => ({ key, count: members.length, sums: sumsOf(target, members) }))\n if (column.type === 'date') return list.sort((a, b) => a.key.localeCompare(b.key))\n /* Largest first by the first sum - in its one currency; groups in two currencies have no common size, so by count. */\n const first = target.columns.find(one => one.total)?.name\n const codes = first ? currenciesOf(list.map(group => group.sums), first) : []\n const size = (group: ReadGroup) => {\n const sum = first ? group.sums[first] : undefined\n return typeof sum === 'number' ? Math.abs(sum) : codes.length === 1 && sum ? Math.abs(sum[codes[0]] ?? 0) : undefined\n }\n return list.sort((a, b) => {\n const [x, y] = [size(a), size(b)]\n return x !== undefined && y !== undefined && codes.length <= 1 ? y - x : b.count - a.count\n })\n}\n\n/** The address of the target's list screen with the conditions it takes, and the conditions it does not. */\nexport function screenAddress(target: ReadTarget, criteria: Record<string, unknown>): { href: string; applied: string[]; notApplied: string[] } | undefined {\n const screen = target.screen\n if (!screen) return undefined\n const params = new URLSearchParams()\n for (const [name, value] of Object.entries(screen.params(criteria))) if (value !== undefined && value !== null && value !== '') params.set(name, String(value))\n const given = Object.keys(criteria)\n const query = params.toString()\n return {\n href: query ? `${screen.route}?${query}` : screen.route,\n applied: given.filter(name => screen.takes.includes(name)),\n notApplied: given.filter(name => !screen.takes.includes(name))\n }\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import { type ToolCategory } from '@things-factory/ai-client-base';
2
2
  import type { GraphqlRunner } from '../data-entry/entry-update.js';
3
- import { type ReadTarget } from './read-target.js';
3
+ import { type DetailRead, type ReadTarget } from './read-target.js';
4
4
  export declare function queryRecords(target: ReadTarget, args: any, context: any, run: GraphqlRunner): Promise<{
5
5
  rejected: boolean;
6
6
  error: string;
@@ -226,3 +226,56 @@ export declare function readCategoryOf(target: ReadTarget, run?: (context: any)
226
226
  * in `readTargets`.
227
227
  */
228
228
  export declare function registerReadTarget(target: ReadTarget): void;
229
+ /** Runs the query as the person with the arguments the model set; the answer as the query returned it. */
230
+ export declare function queryDetail(target: DetailRead, args: any, run: GraphqlRunner): Promise<{
231
+ rejected: boolean;
232
+ error: string;
233
+ refused: {
234
+ name: string;
235
+ code: string;
236
+ }[];
237
+ message: string;
238
+ target?: undefined;
239
+ found?: undefined;
240
+ size?: undefined;
241
+ answer?: undefined;
242
+ } | {
243
+ rejected: boolean;
244
+ error: string;
245
+ message: string;
246
+ refused?: undefined;
247
+ target?: undefined;
248
+ found?: undefined;
249
+ size?: undefined;
250
+ answer?: undefined;
251
+ } | {
252
+ target: string;
253
+ found: boolean;
254
+ message: string;
255
+ rejected?: undefined;
256
+ error?: undefined;
257
+ refused?: undefined;
258
+ size?: undefined;
259
+ answer?: undefined;
260
+ } | {
261
+ rejected: boolean;
262
+ error: string;
263
+ size: number;
264
+ message: string;
265
+ refused?: undefined;
266
+ target?: undefined;
267
+ found?: undefined;
268
+ answer?: undefined;
269
+ } | {
270
+ target: string;
271
+ answer: any;
272
+ message: string;
273
+ rejected?: undefined;
274
+ error?: undefined;
275
+ refused?: undefined;
276
+ found?: undefined;
277
+ size?: undefined;
278
+ }>;
279
+ export declare function detailCategoryOf(target: DetailRead, run?: (context: any) => GraphqlRunner): ToolCategory;
280
+ /** What an application calls at boot to let the assistant read one answer of its API. A mode opens it by key in `readTargets`. */
281
+ export declare function registerDetailRead(target: DetailRead): void;
@@ -4,6 +4,9 @@ exports.queryRecords = queryRecords;
4
4
  exports.openScreen = openScreen;
5
5
  exports.readCategoryOf = readCategoryOf;
6
6
  exports.registerReadTarget = registerReadTarget;
7
+ exports.queryDetail = queryDetail;
8
+ exports.detailCategoryOf = detailCategoryOf;
9
+ exports.registerDetailRead = registerDetailRead;
7
10
  /*
8
11
  * The tools of an AI 조회 target (operato-application/design/ai/read-targets.md §4, §5).
9
12
  *
@@ -205,4 +208,76 @@ function registerReadTarget(target) {
205
208
  (0, read_target_js_1.declareReadTarget)(target);
206
209
  (0, ai_client_base_1.registerToolCategory)(readCategoryOf(target));
207
210
  }
211
+ /* ── One answer of a query (DetailRead) ───────────────────────────────────────────────────────────────────── */
212
+ function argSchema(arg) {
213
+ const type = arg.type === 'number' ? 'number' : arg.type === 'integer' ? 'integer' : arg.type === 'boolean' ? 'boolean' : 'string';
214
+ const said = [arg.description, arg.type === 'date' ? 'YYYY-MM-DD' : undefined, arg.type === 'enum' ? `one of: ${arg.values.join(', ')}` : undefined].filter(Boolean).join('. ');
215
+ return { type, ...(said ? { description: said } : {}) };
216
+ }
217
+ /** Runs the query as the person with the arguments the model set; the answer as the query returned it. */
218
+ async function queryDetail(target, args, run) {
219
+ const variables = {};
220
+ const refused = [];
221
+ for (const arg of target.args ?? []) {
222
+ const value = args?.[arg.name];
223
+ if (value === undefined || value === null || value === '') {
224
+ if (arg.required)
225
+ refused.push({ name: arg.name, code: 'required' });
226
+ continue;
227
+ }
228
+ const { read, code } = (0, entry_target_js_1.readFieldValue)({ name: arg.name, type: arg.type === 'string' ? 'text' : arg.type, values: arg.values }, value);
229
+ if (read === undefined)
230
+ refused.push({ name: arg.name, code: code ?? 'unreadable' });
231
+ else
232
+ variables[arg.name] = read;
233
+ }
234
+ if (refused.length)
235
+ return { rejected: true, error: 'argument-unreadable', refused, message: `these arguments are missing or do not fit their type: ${refused.map(one => `${one.name} (${one.code})`).join(', ')}. Fix them and call again.` };
236
+ let answer;
237
+ try {
238
+ answer = await run(target.query, variables);
239
+ }
240
+ catch (error) {
241
+ return { rejected: true, error: 'query-failed', message: `it could not be read: ${error?.message ?? error}` };
242
+ }
243
+ if (answer.errors?.length)
244
+ return { rejected: true, error: 'query-failed', message: `it could not be read: ${answer.errors.map(one => one.message).join('; ')}` };
245
+ const root = (0, entry_target_js_1.rootFieldOf)(target.query, 'query').replace(/^Query\./, '');
246
+ const value = answer.data?.[root];
247
+ if (value === null || value === undefined)
248
+ return { target: target.key, found: false, message: 'nothing was found for these arguments - say so; do not fill it in.' };
249
+ const size = JSON.stringify(value).length;
250
+ if (size > read_target_js_1.MAX_DETAIL_CHARS)
251
+ return { rejected: true, error: 'answer-too-large', size, message: `the answer runs to ${size} characters, more than ${read_target_js_1.MAX_DETAIL_CHARS} - narrow the arguments, or read the list it is made of.` };
252
+ return { target: target.key, answer: value, message: 'answer from these fields; every number you say comes from them. Amounts are in the currency beside them - never add two currencies into one number.' };
253
+ }
254
+ function detailCategoryOf(target, run = entry_tools_js_1.runAsCaller) {
255
+ const door = (0, entry_target_js_1.rootFieldOf)(target.query, 'query');
256
+ const name = (0, read_target_js_1.detailToolName)(target.key);
257
+ return {
258
+ name: (0, read_target_js_1.readCategoryName)(target.key),
259
+ description: `data read: ${target.key}`,
260
+ guidance: `- To answer about ${target.description.replace(/\.$/, '')}, call ${name}. Every number you say comes from its answer.`,
261
+ specs: [
262
+ {
263
+ kind: 'read',
264
+ name,
265
+ /* The person must be able to run the query on its screen - the tool is not a second way in. */
266
+ doors: [door],
267
+ description: `Read ${target.description}`,
268
+ schema: {
269
+ type: 'object',
270
+ ...((target.args ?? []).some(one => one.required) ? { required: (target.args ?? []).filter(one => one.required).map(one => one.name) } : {}),
271
+ properties: Object.fromEntries((target.args ?? []).map(arg => [arg.name, argSchema(arg)]))
272
+ },
273
+ builder: (args, context) => queryDetail(target, args, run(context))
274
+ }
275
+ ]
276
+ };
277
+ }
278
+ /** What an application calls at boot to let the assistant read one answer of its API. A mode opens it by key in `readTargets`. */
279
+ function registerDetailRead(target) {
280
+ (0, read_target_js_1.declareDetailRead)(target);
281
+ (0, ai_client_base_1.registerToolCategory)(detailCategoryOf(target));
282
+ }
208
283
  //# sourceMappingURL=read-tools.js.map