본문으로 건너뛰기

5.9. TypeScript SDK

개요​

이 장은 TypeScript SDK @mindwiki/plugin-sdk 가 내보내는 이름을 모두 정리합니다. 패키지는 serve · 서명 · 오류 · 콜백 · 프로토콜 타입을 한 진입점에서 내보냅니다. 설치 방법과 가장 작은 예시를 먼저 보이고, 이어서 이름을 묶음별 표로 적습니다.

패키지와 버전​

항목값
패키지 이름@mindwiki/plugin-sdk(버전 0.1.0)
Node.js22.18 이상(engines.node: ">=22.18")
모듈 형식ES 모듈만("type": "module"). require 로는 불러올 수 없음
의존성없음(Node.js 내장 모듈 node:http · node:crypto 만)
진입점dist/index.js, 타입은 dist/index.d.ts

Node.js 22.18 이상은 .ts 파일의 타입 표기를 지우고 바로 실행합니다. 그래서 플러그인을 빌드 단계 없이 node main.ts 로 띄울 수 있습니다. 예시 플러그인 plugins/messenger-relay 가 이 방식을 씁니다.

설치​

제품과 함께 받는 배포 파일 mindwiki-plugin-sdk-0.1.0.tgz 를 설치합니다. 의존성이 없으므로 인터넷 없이 파일 하나로 설치됩니다.

npm install ./mindwiki-plugin-sdk-0.1.0.tgz

배포 파일이 없으면 MindWiki 레포에서 직접 만듭니다.

cd sdk/ts && npm run build && npm pack # mindwiki-plugin-sdk-0.1.0.tgz

가장 작은 플러그인​

시작 틀 sdk/template/ts/main.ts 를 설치한 패키지 기준으로 고친 것입니다.

import { createServer } from 'node:http';
import { type Manifest, serve, type ToolResult } from '@mindwiki/plugin-sdk';

const manifest: Manifest = {
id: 'template-plugin-ts',
version: '0.1.0',
title_i18n: { ko: '새 플러그인(TS)', en: 'New plugin (TS)' },
capabilities: ['tools'],
tools: [{ id: 'echo', read_only: true, description: '받은 글을 그대로 돌려준다.',
input_schema: { type: 'object', properties: { text: { type: 'string' } } } }],
};

function echo(args: Record<string, unknown>): ToolResult {
if (typeof args.text !== 'string') return { text: 'text 가 필요합니다', is_error: true };
return { text: args.text };
}

// 지금 비밀(PLUGIN_SECRET)과, 비밀을 바꾸는 동안의 새 비밀(PLUGIN_SECRET_NEXT)
function secretsFromEnv(env = process.env): Record<string, string> {
const secrets: Record<string, string> = {};
if (env.PLUGIN_SECRET) secrets.current = env.PLUGIN_SECRET;
if (env.PLUGIN_SECRET_NEXT) secrets.next = env.PLUGIN_SECRET_NEXT;
return secrets;
}

const handler = serve(manifest, { tools: { echo: (_r, args) => echo(args) } },
{ secrets: secretsFromEnv() }); // 코드 · 명령 인자에 넣지 않는다
createServer(handler).listen(Number(process.env.PORT || 9100));

공유 비밀은 환경 변수에서 읽습니다. PLUGIN_SECRET 은 지금 비밀이고, PLUGIN_SECRET_NEXT 는 시스템 관리자가 비밀을 바꾸는 동안 넣는 새 비밀입니다. 플러그인이 둘을 함께 받으면 비밀을 바꾸는 동안에도 요청이 거절되지 않습니다. 순서는 4.7. 공유 비밀 바꾸기에 있습니다.

띄우기: serve · Options​

이름시그니처설명
serveserve(manifest: Manifest, h: Handlers, o: Options)node:http 의 createServer 에 넘길 처리 함수를 돌려줍니다
Options인터페이스공유 비밀 · 경로 접두사 · 시계 · 로그 · 몸통 한도
PROTOCOLconst PROTOCOL = 1SDK 가 쓰는 프로토콜 버전

serve 가 돌려주는 값은 (req: IncomingMessage, res: ServerResponse) => void 입니다. 동작은 Go SDK 의 Serve 와 같습니다.

  • 모든 요청의 서명을 확인합니다. 서명이 틀리면 401 bad_signature 로 답합니다.
  • GET /manifest 와 GET /health 에 답합니다. health 처리기가 없으면 { ok: true, version } 으로 답합니다.
  • manifest.protocol 이 비었으면 [1] 로 채웁니다.
  • 처리기가 PluginError 를 던지면 그 status 와 code 로 답합니다. 다른 예외는 500 retry 로 답합니다.
  • 같은 경로와 같은 x-mindwiki-delivery-id 의 요청에는 첫 답(500 미만)을 다시 줍니다. 최근 1,000건을 메모리에 둡니다.
  • 몸통이 maxBody 를 넘으면 413 permanent 로 답합니다.

Options 의 필드는 다음과 같습니다.

이름타입설명
secretsRecord<string, string>공유 비밀(필수). 바꾸는 동안 둘. 빈 값은 쓰지 않음
pathPrefixstring플러그인이 앞부분 경로 아래에 있을 때 끝점 앞의 경로
now() => number1970년부터의 초를 돌려주는 시계(시험용)
log(msg: string, err: unknown) => void처리기 오류를 기록할 곳. 기본 console.warn
maxBodynumber요청 몸통의 최대 크기. 기본 8 MiB

처리기: Handlers​

Handlers 는 인터페이스입니다. 끝점마다 처리 함수를 필드로 둡니다. 없는 끝점은 not_found 로 답합니다. 처리 함수는 값을 돌려주거나 Promise 를 돌려줄 수 있습니다(Awaitable<T>).

이름타입 · 시그니처끝점
health() => HealthReportGET /health
verify(r: Request) => voidPOST /config/verify
pull(r: Request, input: PullInput) => PullPagePOST /sync/pull
push(r: Request, input: PushInput) => PushResultPOST /sync/push
actionsRecord<string, (r, input: ActionInput) => ActionResult>POST /actions/{id}
toolsRecord<string, (r, args: Record<string, unknown>) => ToolResult>POST /tools/{id}
webhook(r: Request, input: WebhookInput) => WebhookResultPOST /webhook
notify(r: Request, input: NotifyInput) => NotifyResultPOST /notify
  • actions · tools 의 키는 manifest 의 id 입니다.
  • verify 가 예외 없이 끝나면 SDK 는 { ok: true } 로 답합니다. verify 가 없을 때도 같습니다.
  • notify 가 없는데 /notify 가 오면 SDK 는 permanent 로 답합니다. 위키는 not_found 를 「받는 사람 없음」으로 처리하기 때문입니다.
  • pull 의 답에 items 가 없으면 SDK 는 빈 배열로 답합니다. webhook 의 ops 도 같습니다.
  • push 의 답에 conflict 가 없으면 SDK 가 ok: true 를 채웁니다. 할 일과 알림의 답에도 ok: true 를 채웁니다.

요청: Request​

이름타입 · 시그니처설명
install · workspacestring설치 ID · 워크스페이스 ID
configRecord<string, unknown>설치 설정
secretsRecord<string, string>이 끝점에 실린 설치 비밀
actorActor{ user, role }. 이름 · 메일 없음
deliveryIdstringX-MindWiki-Delivery-Id. 없으면 빈 문자열
callbackCallback | undefined위키를 다시 호출하는 클라이언트. 할 일 · 도구에만 있음
attempt · maxAttemptsnumber할 일의 X-MindWiki-Attempt(n/max). 없으면 둘 다 0
lastAttemptlastAttempt(): boolean할 일의 마지막 시도인지 알려 줌(maxAttempts > 0 && attempt >= maxAttempts)
signalAbortSignal위키의 요청이 끝나면 중단됨

lastAttempt() 가 참일 때 retry 로 답하면, 위키는 다시 보내지 않고 할 일을 실패로 끝냅니다. 이때는 실패를 행에 적은 뒤 permanent 로 답합니다.

signal 을 외부 호출(fetch)에 넘기면, 위키가 더 기다리지 않는 요청을 멈출 수 있습니다.

타입 · 함수 · 상수​

모든 타입의 필드 이름은 JSON 이름(snake_case) 그대로입니다.

타입필드쓰는 곳
HealthReportok · version? · detail?health 의 답
PullInputentity · cursor · limitpull 의 입력
PullPageitems · next_cursor · more? · estimate?pull 의 답
Itemexternal_id · updated? · title · props? · body_md? · deleted? · url?항목 하나
PushInputentity · external_id · changes · snapshotpush 의 입력
PushResultok? · conflict?: { remote }push 의 답
ActionInputinput · context: { row?, values?, link?, fields?, queued_at?, trigger? }할 일의 입력
ActionResultok? · message?할 일의 답
ToolResulttext · is_error?도구의 답
WebhookInputheaders · body_b64웹훅의 입력
WebhookResultops · pull?웹훅의 답
Opop · entity · external_id? · title? · props? · markdown? · filter? · offset? · section?웹훅 답 · 콜백의 연산
NotifyInputtest · recipient · notification알림의 입력
NotifyResultok? · message?알림의 답
Recipientby 에 따라 email · name+value · handle 가운데 하나(user 는 언제나)받는 사람. 이름은 오지 않음
Notificationid? · kind · mention · title · text · url? · lang · created_at알림 내용. 시험 보내기에는 id 가 없음
Actoruser · role요청의 실행 주체
  • ActionInput.context 의 link 와 fields 는 그 행이 이 설치의 짝일 때만 있습니다.
  • Item.props 에서 키를 빼면 위키는 그 속성을 그대로 둡니다. 값의 모양은 5.4. 값 형식을 따릅니다.

manifest 타입은 Manifest · SecretField · Entity · Field · Action · Tool · NotifySpec · I18n · JsonSchema 입니다. 필드 이름은 manifest JSON 과 같고, 각 필드의 규칙은 5.3. manifest에 있습니다.

함수와 상수는 다음과 같습니다.

이름시그니처설명
conflictconflict(remote: Record<string, unknown>): PushResult외부 값이 snapshot 과 다를 때의 push 답을 만듦
parseAttemptparseAttempt(h: string): [number, number]"3/8" 을 읽음. 모양이 다르면 [0, 0]
recipientValuerecipientValue(r: Recipient): string방식에 맞는 값(이메일 · 속성 값 · 메신저 ID)을 돌려줌
CAP_SYNC · CAP_ACTIONS · CAP_TOOLS · CAP_WEBHOOKS · CAP_NOTIFY문자열 상수capability 이름
RECIPIENT_EMAIL · RECIPIENT_ATTRIBUTE · RECIPIENT_HANDLE문자열 상수받는 방식 이름

오류: PluginError​

이름시그니처status · code
errAutherrAuth(msg: string): PluginError401 auth
errRetryerrRetry(msg: string): PluginError503 retry
errPermanenterrPermanent(msg: string): PluginError422 permanent
errNotFounderrNotFound(msg: string): PluginError404 not_found
errUnknownOutcomeerrUnknownOutcome(msg: string): PluginError502 unknown_outcome
errInvalidInputerrInvalidInput(msg, fix = '', ...fields: FieldError[])400 invalid_input
notifyErrornotifyError(code, msg): PluginError알림 실패. 아래 참고
  • 함수는 PluginError 를 돌려줍니다. 처리기에서 throw 합니다.
  • PluginError 는 Error 를 상속한 클래스입니다. 필드 status · code · fix? · errors? 와 toJSON() 을 가집니다. 생성자는 new PluginError(status, code, message, fix?, errors?) 입니다.
  • FieldError 는 { path, message } 이고, path 는 JSON Pointer 입니다.
  • notifyError 의 code 는 'not_found' · 'retry' · 'auth' · 'permanent' 입니다. 앞의 셋은 같은 이름의 함수와 같고, 그 밖의 값은 permanent 입니다.
  • code 상수: CODE_AUTH · CODE_RETRY · CODE_PERMANENT · CODE_INVALID_INPUT · CODE_NOT_FOUND · CODE_UNKNOWN_OUTCOME.
if (!to) throw notifyError('not_found', 'no such person');

code 마다 위키가 하는 일은 5.5. 오류 code에 있습니다.

콜백: Callback​

이름시그니처설명
Callbacknew Callback(url: string, token: string)r.callback 으로 받음
opsops(key: string, ops: Op[], signal?): Promise<OpResult[]>연산을 50개까지 보냄
readBodyreadBody(key, entity, externalId, section = '', signal?): Promise<Body>짝인 행의 본문을 읽음(할 일만)
OpResultindex · status · code? · error? · ignored? · data?연산 하나의 결과(ok · skipped · error)
Bodymarkdown · rev · edited_at · edited_byreadBody 의 답
CallbackErrorstatus · code콜백 요청 자체의 거절(problem+json)
OpErrorcodereadBody 에서 위키가 거절한 연산
  • key 는 Idempotency-Key 헤더가 됩니다. 키를 비우면 SDK 가 무작위 키를 만듭니다. 다시 보낼 수 있는 일에는 r.deliveryId 를 바탕으로 키를 만듭니다.
  • CallbackError.code 는 bad_token · install_unavailable · rate_limited 등입니다. 목록은 5.6. 콜백 API에 있습니다.
  • OpError.code 는 section_not_found · section_ambiguous · too_large · not_found · forbidden · op_not_allowed 입니다.
  • 콜백은 전역 fetch 로 보내고 리다이렉트를 따라가지 않습니다(redirect: 'error'). 토큰이 위키 주소 밖으로 나가지 않게 하기 위해서입니다.
const rows = await r.callback?.ops(`${r.deliveryId}-rows`,
[{ op: 'read_rows', entity: 'issue', offset: 0 }], r.signal);

서명: sign · verify​

serve 가 서명을 확인하므로 보통은 이 함수들을 직접 쓰지 않습니다. 시험에서, 또는 다른 HTTP 프레임워크에 붙일 때 씁니다.

sign(secret: string, kid: string, time: number, method: string, path: string,
h: Headers, body: Uint8Array): string
verify(secrets: Record<string, string>, sig: string, now: number, method: string,
path: string, h: Headers, body: Uint8Array): void
signingString(t: number, method: string, path: string, h: Headers, body: Uint8Array): Buffer
const MAX_SKEW_SECONDS = 300
type Headers = Record<string, string | string[] | undefined>
이름설명
signX-MindWiki-Signature 값(t=…,kid=…,sha256=…)을 만듭니다. time 은 초입니다
verify서명을 확인합니다. 틀리면 SignatureError 를 던집니다
signingString서명할 문자열을 만듭니다
SignatureError서명 거절 예외. 시각이 5분 넘게 다르면 필드 stale 이 참입니다
MAX_SKEW_SECONDS요청 시각과 플러그인 시계의 허용 차이(300초)
Headers헤더 모음(소문자 이름)

헤더 이름 상수는 소문자 값입니다: HEADER_SIGNATURE · HEADER_PROTOCOL · HEADER_INSTALL · HEADER_REQUEST_ID · HEADER_DELIVERY_ID · HEADER_CALLBACK_TOKEN · HEADER_CALLBACK_URL · HEADER_ATTEMPT. 서명 문자열의 규칙은 5.2. 요청 헤더와 서명에 있습니다.

시험​

SDK 자체의 시험은 Node.js 내장 시험 도구(node --test)로 실행합니다. 플러그인 시험도 같은 방식으로 쓸 수 있습니다. 시작 틀의 시험은 node --test main.test.ts 로 실행합니다.

규약 검사는 Go 의 devharness 로 실행합니다. 다음 명령은 MindWiki 레포 루트에서 실행합니다.

WIKI_PLUGIN_SECRET=local-test-only \
go run openmaru.io/cogentai/mindwiki/sdk/go/cmd/devharness -url http://127.0.0.1:9100 check

관련 문서​