본문으로 이동

제품

Company Workspace

공개 API로 만든 Roye의 회사 제품입니다. 회사의 헌장, 팀, 임명을 관리하고, 임명자마다 모듈 ID를 고용 상태에 맞춰 유지합니다. 계약 2에서는 관리형 에이전트, 예산, 정책에 따른 운영이 더해집니다.

로컬 미리보기

계약 1과 2는 로컬 서비스에서만 동작하는 미리보기입니다. 버전을 고정할 수 없고, 호스팅하거나 공개하지 않았으며, 바뀔 수 있습니다. Roye-Contract-Version이 없는 요청은 계약 1로 처리됩니다.

빠른 시작

신뢰할 수 있는 백엔드가 헌장과 바인딩을 직접 정해 회사를 만들고, 설정이 끝나면 채용합니다. 보내기 전에 idempotencyKey를 입력과 함께 저장하세요. 계약 1에서는 직접 호스팅하는 프로세스가 실제 일을 합니다(customer_hosted).

backend.ts
import { Roye } from '@roye-ai/client';

// Trusted backend, server-side only: the management key never reaches a browser.
const roye = new Roye({ baseURL, token: () => process.env.ROYE_PROJECT_KEY!, projectId, environment: 'development', intents });

// An explicit charter and bindings. Persist the key with the input first.
const company = await roye.companies.create({
  displayName: 'support-desk',
  charter: { purpose: 'Answer customer tickets and keep the answers current.' },
  bindings: [
    { module: 'communication', create: { displayName: 'support-desk' } },
    { module: 'knowledge', create: { displayName: 'support-desk' } },
  ],
  idempotencyKey: 'cmp-support-desk-1',
});
// Setup continues after create returns. An expired wait returns the latest state and cancels nothing.
const state = await company.ready({ waitMs: 20_000 });
const workspace = await company.module('communication');
const space = await company.module('knowledge');
hire.ts
const writer = await company.appointments.hire({
  responsibility: 'Draft answers to open tickets.',
  roleLabel: 'Support writer',
  execution: { kind: 'customer_hosted' },
  idempotencyKey: 'apt-writer-1',
});
await writer.ready({ waitMs: 20_000 });

관리형 에이전트는 직접 만든 템플릿으로 시작하기를 보세요.

계약 1과 계약 2

계약 2 요청에는 매번 Roye-Contract-Version: 2를 보내거나 roye.companies.v2를 쓰세요. 응답에는 처리한 버전이 담기고, 다른 값을 보내면 contract_version_unsupported를 받습니다. SDK는 HTTP 위에 로컬 검사만 더합니다. 계약 1에서는 다음이 다릅니다.

  • customer_hosted만 됩니다. 생성할 때 예산이나 정책을 넣으면 unsupported_capability입니다.
  • 사용량, 운영, 조회 라우트는 contract_version_unsupported입니다.
  • Work 바인딩이 없고, 인수인계 항목에도 work_assignment, unsent_question이 없습니다.
  • 관리형 임명자와, 정책이나 Work 바인딩이 있거나 한 번이라도 manual을 벗어난 회사는 목록과 이벤트에 나오지 않고, 이름으로 요청해도 거부됩니다. 이런 회사는 계속 계약 2 전용입니다. 관리형 임명자를 둔 적이 있는 회사는 보관하거나 삭제할 수 없습니다.

개념

  • cmp_ 회사: 헌장, 수명 주기, 준비 상태.
  • pol_ 운영 정책(policyRevision).
  • tem_ 팀. 상위 팀과 팀장을 둘 수 있습니다.
  • apt_ 임명: 사람, 프로세스 또는 관리형 에이전트이며, 플랫폼 액터와 모듈 주체를 가집니다.
  • prv_ 인사 리비전: 임명이 바뀔 때마다 남는 불변 기록이며, 바꾼 주체도 남습니다.
  • mbd_ 모듈 리소스 하나와의 바인딩. 모듈마다 하나입니다.
  • cst_ 설정: 변경에 필요한 모듈 호출을 키와 함께 남깁니다.
  • hof_ 인수인계: 종료된 임명자가 아직 맡고 있던 일.

리소스는 프로젝트와 환경 하나에 속합니다. ID 형식은 해석하지 마세요. 준비 상태는 읽을 때 계산합니다. …는 /v1/companies/{cmp}입니다.

자격 증명과 권한

자격 증명보유자할 수 있는 일
관리 키(ryk_)백엔드일반 라우트 전부입니다.
개발자 로그인콘솔읽기, 설정 재진행, 인수인계 항목 처리입니다. 시크릿은 보지 못합니다.
관리자 베어러(rcp_)별도의 백엔드GET …/manager/grant, POST …/manager/personnel, GET …/manager/appointments/{apt}만 호출하며, 이 라우트는 다른 자격 증명으로 호출할 수 없습니다.
모듈 자격 증명(rac_, rkt_, rwt_)모듈 프로세스호출할 수 없습니다(403 forbidden).

관리자 권한, 인사 제안 결정, 설정 넘겨받기, managementOwnerRequired: true인 인수인계 항목에는 현재 조직 소유자가 필요하며, 리플레이 전에도 다시 확인합니다. GET /v1/companies/management-eligibility는 organizationOwner 값을 알려 주지만 참고용입니다. 직함, 역할 라벨, 보고 체계는 권한을 주지 않습니다.

수명 주기

상태동작
provisioning설정이 실행 중이거나 막혔습니다. 이름, 헌장, 팀은 고칠 수 있지만 채용은 안 됩니다.
open채용, 임명과 팀 변경, 인수인계 항목 처리를 할 수 있습니다.
hired, suspended일시 정지(suspend)하면 Communication 액터를 막고 Knowledge 토큰을 철회합니다. 재개하면 둘 다 되돌립니다.
ending계약 2: 세션이 그 임명자에게 보낸 작업을 취소한 뒤 ended가 됩니다.
ended모듈 주체는 퇴출(retire)되고, 액터는 다시 쓰지 않으며, 인수인계가 열립니다. 끝나지 않은 채용은 setup_cancelled로 끝납니다.
archived모드가 none이 되고 팀, 임명, 세션이 끝나며 모듈 바인딩이 해제됩니다. 이후에는 인수인계 withdraw와 재시도, 설정 재진행, 바인딩 해제, 삭제만 받고, 다른 변경은 모두 company_not_open입니다. 복원은 없습니다.
deleting, deleted보관 설정이 끝난 뒤입니다. deleteCreatedResources를 주면 회사가 만든 모듈 리소스도 지웁니다. 삭제는 단계별로 진행되며 멱등입니다.

임명마다 설정은 하나만 실행됩니다. 설정이 실행 중이거나 막혀 있으면 변경은 setup_incomplete를 받고, 종료, 교체, 보관은 그 설정을 취소합니다. 교체는 한 번의 커밋으로 후임자를 채용하고 전임자를 종료합니다. 응답은 커밋 시점의 스냅샷입니다.

appointments.ts
// Each change needs the revision you last read and a key. Revise records a personnel revision.
const current = await writer.get();
await writer.revise({ expectedRevision: current.revision, changes: { roleLabel: 'Senior support writer' }, idempotencyKey: 'apt-writer-revise-1' });

// Replace creates the successor with its own actor and hire setup and ends the writer as replaced.
const replaced = await writer.replace({
  expectedRevision: (await writer.get()).revision,
  successor: { responsibility: 'Draft answers to open tickets.', roleLabel: 'Support writer', execution: { kind: 'customer_hosted' } },
  idempotencyKey: 'apt-writer-replace-1',
});

직접 만든 템플릿으로 시작하기

템플릿은 앱이 가진 데이터입니다. 역할 이름과 지시문, 초기 인력, 계획과 예산 기본값을 앱에 두고, 계약 2 생성 요청(charter, bindings, budget, policy)으로 풀어서 보냅니다. Roye에는 고객용 템플릿 목록이 없고, 생성 요청에 template을 넣으면 400 invalid_request입니다.

계약 2에서는 회사를 만들고 인력을 채운 뒤, 소유자가 정책을 승인하면 시작합니다. roye.companies.v2.launch()가 아래 호출을 차례로 실행하며, 시작 전용 라우트는 없습니다.

단계호출규칙
1. 생성풀어 낸 policy를 담은 POST /v1/companies응답을 놓치면 생성 키로 복구합니다. 새 키로 다시 보내지 마세요.
2. 준비 상태GET …/readiness?waitMs=20000준비될 때까지 반복합니다.
3. 채용initialStaff 역할마다 POST …/appointmentsmanaged로 채용하며, 페르소나는 역할에서, 프로필과 모델은 agent에서 가져옵니다. 임명자마다 준비될 때까지 기다리세요.
4. 읽기GET /v1/companies/{cmp}policyRevision, resolvedPolicy, controlRevision을 한 번의 읽기에서 가져옵니다.
5. 승인Roye 밖resolvedPolicy를 보여 주세요. 승인을 받았다고 간주하지 마세요.
6. 시작POST …/start409 revision_conflict면 다시 읽고 다시 묻습니다.

채용 키와 시작 키는 생성 키에서 파생됩니다(launch.http). 그래서 중단된 실행을 다시 돌려도 원래 결과가 나올 뿐, 채용이나 시작이 두 번 일어나지 않습니다. launch()는 대기 시간이 끝나면 승인 전에 started: false로 멈춥니다. 임명자가 대기 중이거나 막혔거나 제안 상태일 때도 멈추며, 이때 unready가 그 임명자를 가리킵니다. 같은 키와 같은 maxOutputTokens로 다시 호출하세요. 이미 시작된 회사는 approve를 건너뜁니다.

launch.ts
// Contract 2 preview: the documented launch sequence through the SDK. Persist the create key first.
// The template is your app's data: resolve its roles, staffing and defaults into the explicit create.
const result = await roye.companies.v2.launch({
  idempotencyKey: 'launch-beta-1',
  displayName: 'Beta launch',
  charter: { purpose: 'Launch the beta notes.' },
  bindings: [
    { module: 'communication', create: { displayName: 'Communication' } },
    { module: 'knowledge', create: { displayName: 'Knowledge' } },
    { module: 'work', create: { displayName: 'Work board' } },
  ],
  budget: { limitCredits: 2000 },
  policy: myTemplate.policy, // budget.reserveCredits below the limit
  agent: { profile: { id: 'text-standard', revision: '2' }, model: '<enabled model>' },
  approve: async (review) => askOwner(review.resolvedPolicy, review.policyRevision),
});
if (!result.started) console.log(result.readiness); // resumable: call launch again with the same key
launch.http
# Persist the create key with its body before the create.
POST /v1/companies
Roye-Contract-Version: 2

{ "idempotencyKey": "launch-beta-1", "displayName": "Beta launch", "charter": { … }, "bindings": [ … ], "budget": { "limitCredits": 2000 }, "policy": { …resolved by your app… } }

# Each staffingPlan hire:  hi_ + first 40 hex of sha256("launch-beta-1" + "\n" + role)
POST /v1/companies/{companyId}/appointments
{ "idempotencyKey": "hi_…", "role": "writer", "execution": { "kind": "managed", … }, … }

# After the owner approves:  st_ + first 40 hex of sha256("launch-beta-1" + "\n" + policyRevision + "\n" + controlRevision)
POST /v1/companies/{companyId}/start
{ "idempotencyKey": "st_…", "policyRevision": "pol_…", "expectedControlRevision": 3 }

agent에는 초기 채용자 모두가 쓸 Agents 프로필과 모델을 적습니다. 그래서 Roye가 유료 모델을 대신 고르는 일은 없습니다. 앱이 받은 브리프는 헌장의 목적이 됩니다. 역할에 deliverableGrants가 있으면 회사 Knowledge 공간에 Deliverables 컬렉션이 생기고, planner.outputSchemaVersion: plan.draft-6을 쓰면 세션이 더 진행할 수 없게 된 작업을 계획 단계에서 취소하고 새 작업으로 바꿀 수 있습니다.

예제 앱은 launch-team 템플릿을 apps/roye-company-example/src/templates.ts에 두고, 시작 화면에 앱 데이터로 보여 줍니다.

관리형 임명자

계약 2에서는 채용하거나 후임자를 정할 때 managed를 쓸 수 있습니다. 키를 뺀 Agents 계약 2 정의 본문(페르소나, 프로필, 모델, 선택적 출력 스키마)을 보냅니다. Agents가 거부할 정의는 채용과 함께 거부되고, 프로젝트의 정의 할당량을 넘으면 429 quota_exceeded입니다.

설정이 파생 키로 정의를 만들므로 재시도해도 같은 정의를 돌려받습니다. 그 전까지 execution.agentRef는 null입니다. 정의는 회사가 없어져도 남습니다. 고칠 때는 …/revisions에 changes.definition을 보내며, 운영 주체는 고칠 수 없습니다.

준비 상태의미
pending아직 정의가 없습니다(setup_incomplete).
readyAgents가 사용 가능으로 봅니다.
blockedAgents에서 바로 읽은 사유입니다. definition_archived, definition_purged, profile_retired, model_unavailable, accounting_unavailable, agents_unavailable.
managed.ts
// Company contract 2 is a preview selected per request through roye.companies.v2; it never pins.
const preview = roye.companies.v2.get(companyId);
const agent = await preview.appointments.hire({
  responsibility: 'Answer customer tickets.',
  roleLabel: 'Support agent',
  // The Agents contract 2 definition body without its key: Company derives the key from the setup step.
  execution: {
    kind: 'managed',
    definition: { persona: { instructions: 'Answer tickets briefly.' }, profile: { id: 'text-standard', revision: '2' }, model },
  },
  idempotencyKey: 'apt-support-agent-1',
});
// Pending until the setup created the definition; then Agents eligibility is read live.
const readiness = await agent.ready({ waitMs: 20_000 });
const view = await agent.get(); // view.execution: { kind: 'managed', agentRef: { definitionId, revision } }

예산

계약 2 생성 요청에 budget: { limitCredits, reserveCredits? }를 정수 크레딧으로 넣을 수 있습니다. 크레딧은 가격이 아닙니다. 예비분 기본값은 0이고 한도보다 작아야 합니다(400 invalid_request). 회사는 예산을 budgetRef로 가리키며, 없으면 null입니다. 관리형 턴의 비용은 이 예산에서 잡아 두고, 예비분은 검증된 검토자의 검토 턴만 씁니다. 사용량 응답에는 금액이 들어 있지 않습니다. 내야 할 금액은 결제의 Company 예산에서 확인하세요.

`GET …/usage` 필드의미
limit, reserveCredits직접 정한 한도와 예비분입니다.
pending.count보고된 비용이 아직 오지 않은 관리형 턴의 수입니다.
unknown.count사용량 근거가 없는 관리형 턴의 수입니다. 개수일 뿐이며 비용 0이라는 뜻이 아닙니다.
state, revisionopen, exhausted, blocked 중 하나와, 증액에 넣을 리비전입니다.

POST …/budget/raise에는 그 revision과 현재 한도보다 큰 limitCredits를 보냅니다(아니면 400 invalid_request). 소진된 예산은 다시 열리지만 차단은 풀리지 않고, 보관된 회사의 증액은 거부합니다(company_not_open).

budget.ts
// Contract 2 preview: a company created with a finite budget in credits (the reserve defaults to 0).
const budgeted = await roye.companies.v2.create({
  displayName: 'launch-desk',
  charter: { purpose: 'Ship the launch notes within budget.' },
  bindings: [],
  budget: { limitCredits: 5_000 },
  idempotencyKey: 'cmp-launch-desk-1',
});
const usage = await budgeted.usage();
// usage carries the limit, the reserve, the state and the pending and unknown counts, with no spent amount.
const raised = await budgeted.budget.raise({
  expectedRevision: usage.revision,
  limitCredits: 8_000,
  idempotencyKey: 'budget-raise-1',
});

운영 정책과 제어

계약 2 정책은 역할과 권한, 초기 인력, 플래너, 검토 라우팅, personnel 한도를 정합니다. 같은 정책은 늘 같은 policyRevision을 가지므로, 검토한 리비전을 그대로 시작하면 됩니다. 예비분은 정책의 budget.reserveCredits가 정합니다. 그래서 생성 본문에 reserveCredits를 넣으면 invalid_request이고, 예비분이 0보다 크면 예산이 있어야 합니다. 정책은 manual 모드에서만 POST …/policy로 바꿉니다.

동작본문결과
POST …/startpolicyRevision, expectedControlRevision정책이 있고 열려 있으며 준비된 회사를 manual에서 시작합니다. 202, 모드 starting입니다. 10분 안에 연결되지 않으면 실패하고(activation_expired, activation_failed) manual로 돌아갑니다.
POST …/pauseexpectedControlRevision(선택)autonomous에서 paused로 바뀝니다. 세션과 권한은 남고, Work 클레임은 시도 횟수를 그대로 둔 채 기다립니다.
POST …/resumemode, expectedControlRevisionautonomous를 보내면 같은 세션을 이어 가거나 403 standing_grant_withdrawn을 받습니다. manual을 보내면 세션을 끝냅니다.
POST …/stopexpectedControlRevisionstarting, autonomous, paused에서 manual로 돌아가고, 권한은 회수됩니다.

autonomous에서는 회사의 운영 세션이 운영 주체가 됩니다. 운영 주체는 회사가 열려 있고 autonomous이며, 연결된 세션에서 현재 리비전을 들고 있을 때만 다른 모듈을 호출할 수 있습니다. 아니면 company_not_active나 stale_company_revision을 받습니다.

operation.ts
// Contract 2 preview: an operating policy at create; the policy's reserve sets the budget's reserve.
const policy = {
  roles: [
    { role: 'lead', title: 'Lead', instructions: 'Plan the launch.', turnKinds: ['plan', 'work'], workGrants: ['plan', 'work'] },
    { role: 'editor', title: 'Editor', instructions: 'Review every deliverable.', turnKinds: ['review'], workGrants: ['review'] },
  ],
  initialStaff: ['lead', 'editor'],
  planner: { role: 'lead', outputSchemaVersion: 'plan.1' },
  reviewRouting: { defaultReviewerRole: 'editor', byTaskKind: {} },
  personnel: { rosterMax: 5, hireableRoles: ['editor'], minHireIntervalMs: 0 },
  budget: { reserveCredits: 1_000 },
};
const operated = await roye.companies.v2.create({
  displayName: 'launch-desk',
  charter: { purpose: 'Run the launch.' },
  bindings: [],
  budget: { limitCredits: 5_000 },
  policy,
  idempotencyKey: 'cmp-launch-desk-2',
});
await operated.ready({ waitMs: 20_000 });
// Start the exact policy revision you reviewed, at the control revision you read.
const control = await operated.control();
const started = await operated.operation.start({
  policyRevision: operated.view.policy!.policyRevision,
  expectedControlRevision: control.controlRevision,
  idempotencyKey: 'start-1',
});
// started.control.mode is 'starting'; read control() until it is 'autonomous' with a session.
await operated.operation.stop({ expectedControlRevision: (await operated.control()).controlRevision, idempotencyKey: 'stop-1' });

조회

읽기라우트반환
제어GET …/control모드, controlRevision, 세션, 대기 중인 시작, 이전 세션, 완료.
세션GET …/sessions연결 기록과 시작 결과.
남은 일GET …/obligations모듈별로 잡혀 있거나, 보냈거나, 알 수 없는 작업.
런타임GET …/runtimeruntime_observation이 있을 때 접수 횟수, 활성과 미확인 수, nextWakeAt, 막힌 이유.
운영 세션GET …/sessions/IDhealth, nextWakeAt, awaitingPlanning. 세션마다 /entries(heldReason), /exceptions. 다른 회사의 세션은 404 not_found입니다.
이벤트GET …/events?cursor=폴링 페이지.
세션 이벤트GET …/session-events?cursor=이 회사의 세션에서 생긴 이벤트입니다. 7일 동안 보관하며 waitMs는 없습니다. 더 오래된 커서는 410 cursor_expired입니다.

null 수치는 0이 아니라 모른다는 뜻입니다. next가 있어도 페이지가 짧거나 비어 있을 수 있으니 next가 null이 될 때까지 읽으세요. company.observe()는 두 이벤트 페이지를 읽고 커서 두 개를 담은 token을 돌려줍니다. 저장했다가 다시 넘기고, eventId로 중복을 거르세요. SDK는 모르는 필드를 버립니다.

observe.ts
const company = roye.companies.v2.get(result.company.id);
const obligations = await company.obligations();
const board = await company.module('work');
const { current } = await company.operation.sessions();
const session = company.operation.session(current.sessionId);
const awaiting = (await session.get()).awaitingPlanning;
const stalled = await session.exceptions({ kind: 'stalled' });

// One observation step; persist the token (the two cursors) and pass it back.
let token = loadToken(); // { company, sessions }, or undefined the first time
const step = await company.observe({ token, waitMs: 20000 }); // { companyEvents, sessionEvents, token }
token = step.token;

Work 바인딩과 인사

계약 2에서는 회사에 Work 보드 하나를 바인딩할 수 있습니다. 생성할 때 넣거나 나중에 POST …/bindings로 붙입니다. 채용에 role을 주면 Work 참가자는 그 역할의 권한을, Knowledge 멤버는 역할의 컬렉션을 받습니다. 역할이 없으면 Work 권한도 없습니다. 참가자는 임명자의 다른 주체와 함께 움직입니다.

규칙의미
인원채용, 승인, 교체는 rosterMax 안에 들어야 하며, hired, suspended, ending 임명이 자리를 차지합니다. 넘으면 429 quota_exceeded입니다.
운영 주체라벨, 팀, 관리자만 고치고, 정책에 적힌 항목 종류만 withdraw하며, 자기가 일시 정지한 것만 재개합니다. 준비된 마지막 플래너와 검토자는 남겨 둡니다. 그 밖에는 personnel_authority_exceeded입니다.
보관보드를 닫고(보내지 않은 작업은 취소, 클레임된 작업과 불확실한 작업은 유지) 바인딩을 해제합니다.
제안운영 주체가 정책을 벗어나 채용하면(role_not_hireable, roster_max, hire_interval) 제안이 됩니다. employment: proposed이고 설정도 인원 자리도 없습니다. 7일이 지나거나 보관되면 만료됩니다.
결정리비전을 지정해 POST …/appointments/{apt}/approve나 /reject를 보냅니다. 관리 키나 콘솔만 할 수 있고 운영 주체는 할 수 없습니다. 승인하면 현재 정책과 인원으로 다시 검사한 뒤 승인한 호출자의 자격으로 채용합니다.
work-binding.ts
// Contract 2 preview: bind a Work board and staff it by policy role.
const staffed = await roye.companies.v2.create({
  displayName: 'launch-desk',
  charter: { purpose: 'Run the launch.' },
  bindings: [
    { module: 'communication', create: { displayName: 'launch-desk' } },
    { module: 'knowledge', create: { displayName: 'launch-desk' } },
    { module: 'work', create: { displayName: 'launch-desk' } },
  ],
  policy,
  idempotencyKey: 'cmp-launch-desk-3',
});
const lead = await staffed.appointments.hire({
  responsibility: 'Plan the launch.',
  roleLabel: 'Lead',
  role: 'lead', // its Work participant gets the role's Work grants
  execution: { kind: 'customer_hosted' },
  idempotencyKey: 'apt-lead-1',
});
proposals.ts
// Proposals: hires the operating principal made outside the policy wait for you.
const { items } = await staffed.appointments.list({ employment: 'proposed' });
for (const proposal of items) {
  const handle = staffed.appointments.get(proposal.id);
  if (proposal.proposal?.outsidePolicy.includes('roster_max'))
    await handle.reject({ expectedRevision: proposal.revision, idempotencyKey: `reject-${proposal.id}` });
  else await handle.approve({ expectedRevision: proposal.revision, idempotencyKey: `approve-${proposal.id}` });
}

관리자 권한(POST …/manager-grants, 목록, /{grant}/revoke)은 관리자 베어러에게 기한과 한도가 있는 인사 권한을 줍니다. 시크릿은 한 번만 돌려주며, 리플레이하면 credential.status: not_replayable이니 철회하고 다시 발급하세요. SDK에는 managerGrants, personnelProposals, manager가 있습니다.

관리자 권한규칙
범위적어 둔 대상과 명세에만 hire, suspend, resume, end, replace를 할 수 있습니다. 예산, 정책, 권한 발급은 못 합니다.
검사소유자, 만료, 철회, 자율 운영 상태, 정책, 인원을 확인하고, 리플레이 전에도 다시 확인합니다. 리플레이는 접수 횟수를 쓰지 않습니다.
정책 밖의 요청인사 제안(GET …/personnel-proposals[/{proposal}])이 되며 …/{proposal}/decision으로 결정합니다. 다시 승인해 적용될 때까지 approved_pending이 보입니다.

예정 고용

계약 2 생성 요청에는 employmentProfile(profile: employment-agreement-required-1, employerPartyId)을 넣을 수 있습니다. 기존 방식으로 인력을 배치하려면 이 필드를 빼세요. 고용주는 회사와 같은 프로젝트·환경에 있는 조직 당사자이고, 근로자는 개인이나 에이전트 당사자입니다. 이 프로필을 쓰면 초기 인력은 보류 상태로 두고, 서명 없는 채용과 교체는 받지 않습니다. 서명한 범위를 바꾸려면 새 인텐트와 새 계약이 필요합니다.

단계라우트결과
예약idempotencyKey, employeePartyId, expiresAt, appointment를 담아 POST …/employment-intents. 근로자 당사자마다 하나201과 함께 임명·설정 ID, 임명 명세, revision, digest, agreement: null이 담긴 held 인텐트를 돌려줍니다. expiresAt은 epoch 밀리초 단위의 미래 시각이며, 지금부터 30일 안이어야 합니다.
읽기GET …/employment-intents/{intent}목록 라우트가 없으니 ID를 저장하세요.
계약Agreements API: POST /v1/agreements약관 documentDigest에 인텐트 다이제스트를 넣어 고용주와 근로자 사이의 계약을 만듭니다. 제안한 뒤 각 당사자가 수락합니다. 백엔드 키로 당사자를 대신해 수락할 때는 evidence를 보냅니다.
이행idempotencyKey, expectedRevision, agreementId를 담아 POST …/{intent}/fulfill201과 함께 임명과 설정을 돌려줍니다. 인텐트와 임명에 계약 ID, 약관 리비전, 약관 다이제스트가 남습니다.
해제idempotencyKey, expectedRevision만 담아 POST …/{intent}/release. 다른 필드는 받지 않습니다200. held 인텐트에만 쓸 수 있고, 인력 자리를 비웁니다. 리비전이 최신이 아니면 revision_conflict입니다. expiresAt까지 이행하지 않은 예약도 해제됩니다.
  • 인텐트 라우트는 Roye-Contract-Version: 2로 호출해야 하고(아니면 contract_version_unsupported), 이 프로필로 만든 회사에서만 쓸 수 있습니다(아니면 unsupported_capability).
  • 이행하려면 만료되지 않은 held 인텐트, 성립했거나 활성 상태인 계약, 자격이 유효한 두 당사자가 필요합니다. 당사자나 다이제스트가 다른 계약은 binding_invalid입니다. 계약이 아직 성립하지 않았거나, 당사자의 자격이 유효하지 않거나, 인텐트가 held가 아니면 invalid_transition입니다.
  • 그 계약이 활성 상태이고 두 당사자의 자격이 유효한 동안에만 임명에 일을 맡길 수 있습니다. 계약이 끝나거나 만료되거나, 당사자가 일시 정지되거나 퇴출되면 그때부터 새 일을 맡길 수 없습니다. 계약이 끝난 임명은 회사 스윕이 정리합니다.
  • 임명을 끝내도 계약은 끝나지 않습니다. 계약은 당사자가 POST /v1/agreements/:agreementId/end로 끝냅니다.
employment.http
# Company calls use the Company caller's token or key; each party accepts with its own credential.
POST /v1/companies
Authorization: Bearer <Company management token or key>
X-Roye-Project: <company project>
X-Roye-Environment: development
Roye-Contract-Version: 2
Content-Type: application/json

{ "idempotencyKey": "company-required-1", "displayName": "Release desk", "charter": { "purpose": "Write release notes" }, "bindings": [],
  "employmentProfile": { "profile": "employment-agreement-required-1", "employerPartyId": "<represented organization party>" } }

# Every Company request below carries the same headers.
POST /v1/companies/<companyId>/employment-intents
{ "idempotencyKey": "reserve-1", "employeePartyId": "<person or agent party>", "expiresAt": <future epoch milliseconds>,
  "appointment": { "responsibility": "Draft release notes", "roleLabel": "Writer", "execution": { "kind": "customer_hosted" } } }

201 Created
{ "id": "cei_…", "companyWorkspaceId": "cmp_…", "appointmentId": "apt_…", "setupId": "cst_…", "appointment": { … },
  "revision": 1, "digest": "<64 hex>", "state": "held", "agreement": null, … }

# Agreements API, as the employer: an ordinary agreement whose terms document is the intent digest.
POST /v1/agreements
Authorization: Bearer <employer representative's key or token>
X-Roye-Project: <company project>
X-Roye-Environment: development
Roye-Contract-Version: 1
Content-Type: application/json

{ "idempotencyKey": "employment-1", "partyIds": ["<employer party>", "<employee party>"],
  "terms": { "title": "Writer employment", "documentDigest": "<intent digest>", "attributes": { "role": "Writer" }, "startsAt": null, "expiresAt": null } }
# Offer it, then each party accepts the exact terms.

POST /v1/companies/<companyId>/employment-intents/<intentId>/fulfill
{ "idempotencyKey": "fulfill-1", "expectedRevision": 1, "agreementId": "<formed agreement>" }

201 Created
{ "appointment": { "id": "apt_…", … }, "setup": { "id": "cst_…", … } }

# Lost response: recover under the original caller, contract version and key.
POST /v1/operations/recover
{ "module": "companies", "kind": "employment_intents.fulfill",
  "target": { "companyWorkspaceId": "<companyId>", "employmentIntentId": "<intentId>" }, "idempotencyKey": "fulfill-1" }

GET /v1/companies/<companyId>/setups/<setupId>
# Repair the original setup if blocked; never hire again.

# Instead of fulfilling, release a held intent to free its staffing place.
POST /v1/companies/<companyId>/employment-intents/<intentId>/release
{ "idempotencyKey": "release-1", "expectedRevision": 1 }
employment.ts
// Thin SDK, same HTTP fields and Company authority.
const company = roye.companies.v2.get(companyId);
const reserved = await company.employmentIntents.reserve({
  idempotencyKey: 'reserve-1', employeePartyId, expiresAt,
  appointment: { responsibility: 'Draft release notes', roleLabel: 'Writer', execution: { kind: 'customer_hosted' } },
});
const intent = company.employmentIntents.get(reserved.id); // no request until get()
const exact = await intent.get();
// Each party's own client creates, offers and accepts the agreement through roye.agreements.
// Persist the exact fulfill input, target and key before sending.
const originalSetup = await intent.fulfill({ idempotencyKey: 'fulfill-1', expectedRevision: exact.revision, agreementId });
// Ending the appointment leaves the agreement active; a party ends it with roye.agreements.get(agreementId).end(...).

인수인계

종료나 교체는 인수인계를 엽니다. pendingWork는 require_handoff가 기본값이고 withdraw_undispatched도 됩니다. 14일 마감까지 항목을 최대 1,000개 모으고, 마감이 지나면 closed_unresolved로 닫힙니다.

항목transferwithdraw
communication_request후임자의 액터에게 넘깁니다.요청을 취소합니다.
communication_delivery후임자의 액터에게 넘깁니다.만료되면 closed_by_module_expiry로 닫힙니다.
knowledge_responsibility후임자에게 read와 contribute를 줍니다.not_transferred로 닫힙니다.
work_assignment계약 2: Work에서 재배정합니다.Work에서 회수하거나 reassign_next_plan을 씁니다.
unsent_question계약 2: 후임자의 다음 턴을 위해 남깁니다.회수한 것으로 기록합니다.
original_obligation허용되지 않습니다.허용되지 않습니다. 자격 증명, 클레임, 불확실한 효과는 물려받지 않습니다.
  • 처리마다 파생 키 handoffId_ordinal_dispositionSequence가 있고, 재시도는 같은 키를 씁니다.
  • transfer는 후임자가 준비될 때까지 기다립니다(appointment_not_ready). 검토 중인 작업은 deferred_review로 기다립니다.
  • 운영 중인 회사는 처리하지 않은 항목을 handoffDefaults.withSuccessor에 따라 넘깁니다. 직접 정하려면 먼저 처리하거나 회사를 일시 정지(pause)하세요.
handoffs.ts
// An ended appointment leaves a handoff. Transfer needs a ready successor; withdraw needs none.
const handoff = company.handoffs.get(handoffId);
const { items } = await handoff.get();
for (const item of items.filter((candidate) => candidate.state === 'pending'))
  await handoff.dispose(item.ordinal, {
    disposition: 'transfer',
    successorAppointmentId: replaced.successor.id,
    idempotencyKey: `dispose-${handoffId}-${item.ordinal}-1`,
  });

검증된 완료

바인딩된 보드의 목표가 모두 닫히면 운영 주체가 완료 중지를 요청합니다. 이 요청에는 라우트도 SDK 메서드도 없습니다. Company는 지정한 목표가 모두 그 결과로 닫혔고 열리거나 만료된 목표가 없을 때만 기록합니다. 제어 레코드의 completion에는 목표별 결과와 전체 결과(achieved, partial, abandoned)가 담깁니다. 세션은 completed로 끝나고 권한은 회수되며, 회사는 다시 시작할 수 없습니다(409 invalid_transition).

completion.http
# After the operating principal's completion stop, the control view shows the verified completion.
GET /v1/companies/{companyId}/control
Roye-Contract-Version: 2

200 OK
{ "mode": "manual", "session": null,
  "previousSessions": [ { "sessionId": "aos_…", "reason": "completed", … } ],
  "completion": { "sessionId": "aos_…", "controlRevision": 9, "completedAt": 1767830400000,
                  "goals": [ { "goalId": "wgl_…", "outcome": "achieved", "closeReason": "Launched." } ], "outcome": "achieved" }, … }

브리프와 수락

브리프, 그리고 소유자가 완성된 작업을 수락한 기록은 앱이 가진 데이터입니다. 예제 앱은 브리프마다 company.module('work')로 회사 보드에 Work 목표를 하나 만듭니다. 그 목표의 작업이 Work에서 모두 수락되고 남은 작업이 없으면, 소유자의 수락을 앱 상태에 기록합니다.

Roye는 앱의 브리프나 수락 기록을 따로 저장하지 않습니다. 프롬프트와 결정은 앱 저장소에 그대로 남습니다.

설정과 재진행

모듈 호출은 하나하나가 파생 키를 가진 단계라서, 재시도나 재진행은 원래 리소스를 돌려줍니다. 요청 하나는 호출을 32개까지 진행하고, 나머지는 재진행이나 서버 스윕을 기다립니다.

상태의미
running남은 단계가 있습니다. 일시적인 거부는 다섯 번까지 시도합니다.
blockedstep_failed, authority_revoked, deadline_exceeded 중 하나입니다.
completed, completed_with_skips끝났거나, 대상이 이미 없어 바인딩이 깨졌습니다.
cancelled보관이나 종료로 취소되었습니다. 늦게 생긴 리소스는 정리합니다.

원인을 고친 뒤 새 키로 POST …/setups/{cst}/repair를 호출하세요. 남은 단계는 재진행한 호출자의 권한으로 진행됩니다. 관리자 설정은 adoptManagerAuthority: true, 소유자 권한이 필요한 설정은 adoptOwnerAuthority: true가 필요합니다. 재진행해도 완료된 회사는 다시 시작하지 않습니다.

repair.ts
// A blocked setup keeps its original IDs. Read the failing step, fix the cause, then repair under a new key.
const blocked = await company.setups.get(setupId);
const failing = blocked.steps.find((step) => step.state === 'blocked' || step.state === 'failed');
await company.setups.repair(setupId, { idempotencyKey: 'repair-1' });

엔드포인트

경로는 /v1/companies 아래입니다. 모두 관리 키를 쓰고, 변경 요청은 idempotencyKey를 받습니다. 계약 2 라우트는 위의 각 절에 있습니다.

라우트용도
POST /, GET /, GET …, POST …, POST …/charter, GET …/readiness, …/archive, …/delete회사
POST …/teams, GET …/teams[/{tem}], POST …/teams/{tem}, …/teams/{tem}/dissolve팀
POST …/bindings, GET …/bindings[/{mbd}], POST …/bindings/{mbd}/unbind바인딩
POST …/appointments, GET …/appointments[/{apt}], …/{apt}/readiness, …/{apt}/revisions, /suspend, /resume, /end, /replace임명
GET …/setups[/{cst}], POST …/setups/{cst}/repair설정
GET …/handoffs[/{hof}], POST …/handoffs/{hof}/items/{ordinal}, /retry인수인계

한도

미리보기용 임시값입니다. 넘으면 payload_limit, quota_exceeded 같은 오류로 거부합니다.

한도값
회사프로젝트와 환경마다 10개, 회사마다 바인딩 3개.
팀, 임명팀 50개(깊이 4), 현재 임명 100개.
헌장32 KiB, 컨텍스트 참조 32개, 목표 ID 32개.
정책역할 16개, 초기 인력 32명, 검토 라우트 32개. 역할마다 컬렉션 권한 8개, 지시문 4,000자.
설정단계 1,024개. 24시간 마감이 지나면 막힐 뿐 취소되지는 않습니다.
인수인계항목 1,000개, 14일, 미전송 질문 16개.
관리자 권한활성 8개, 누적 128개, 30일 이내 만료, 대상 16개, 접수 16회.
인사 제안대기 16개, 누적 64개, 48시간 만료.
남은 일바인딩 레코드 500개나 해제된 보드와 워크스페이스 60개를 넘으면 부분 목록 없이 503 unavailable입니다.
대기, 페이지, 보존대기 30초, 페이지당 64개(기본 32개), 리플레이와 이벤트 보존 7일.

이번 미리보기에 없는 것: 호스팅, Agents, Actions, Automation 바인딩, 내보내기, 이벤트 구독, 설정 재진행과 인수인계 처리 외의 콘솔 변경, 예약 스윕, 속도 제한, 과금.

오류

오류는 공통 오류 형식을 씁니다. 다른 프로젝트의 리소스는 not_found로 보입니다.

코드HTTP할 일
invalid_request, payload_limit, unsupported_capability, contract_version_unsupported400, 413입력을 고치거나, 버전 2나 지원되는 옵션을 보내세요.
unauthorized, forbidden, not_found401, 403, 404이 프로젝트의 관리 키를 쓰세요.
authority_revoked, standing_grant_withdrawn, personnel_authority_exceeded403현재 권한으로 재진행하거나, 중지한 뒤 다시 시작하세요.
budget_unavailable404회사에 예산이 없습니다.
not_ready, setup_incomplete, company_not_open, appointment_not_ready, company_not_active, stale_company_revision, already_active409준비 상태, 설정, 제어 뷰를 읽고 기다리거나 재진행하세요.
binding_invalid, binding_broken, artifact_unavailable409리소스를 다시 읽으세요.
idempotency_conflict, revision_conflict, invalid_transition, team_not_empty409원래 작업을 복구하거나, 다시 읽고 새 키로 다시 결정하세요. 팀 해산에는 reassignTo를 쓰세요.
quota_exceeded, rate_limited429인원을 줄이거나, 같은 키로 잠시 뒤 다시 보내세요.
cursor_expired, operation_replay_expired410현재 상태를 읽으세요. 삭제된 회사는 복구할 수 없습니다.
operation_pending, unavailable202, 503원래 작업의 상태를 확인하거나, 같은 키와 입력으로 다시 시도하세요.

복구

결과가 불확실한 호출을 새 키로 재시도하지 마세요. 같은 입력을 다시 보내거나, 원래 호출자로 module: companies, 종류, 대상, 키를 담아 POST /v1/operations/recover를 호출하세요. 다른 계약 버전에서 같은 키를 쓰면 idempotency_conflict입니다.

상황할 일
생성, 시작, 증액, 전환, 채용 응답 유실create(빈 대상), start, budget.raise, policy.revise, pause, resume, stop, appointments.hire를 복구한 뒤 설정, …/sessions의 starts, 사용량, 제어 뷰를 읽으세요. 다시 채용하지 마세요.
예약, 해제, 이행 응답 유실계약 2와 원래 키로 복구하세요. employment_intents.reserve의 대상은 { companyWorkspaceId }, employment_intents.release와 employment_intents.fulfill의 대상은 { companyWorkspaceId, employmentIntentId }입니다. 이행은 그 뒤 권한이 바뀌어도 복구할 수 있습니다. 복구한 뒤 인텐트와 설정을 읽고, 다시 채용하지 마세요.
처리 응답 유실같은 처리와 키로 다시 보내세요. 다른 처리는 새 요청입니다.
관리자 시크릿 유실철회하고 다시 발급하세요.
삭제 중단같은 키로 다시 보내면 삭제가 이어집니다.
recovery.ts
// The create response was lost and the company ID is unknown. Recover by the original key alone,
// with the credential that performed it.
const original = await roye.operations.recover({
  module: 'companies',
  kind: 'create',
  target: {},
  idempotencyKey: 'cmp-support-desk-1',
});
// The same intent with the same key replays the original commit-time snapshot.
const again = await roye.companies.create(sameInputAsBefore); // idempotencyKey: 'cmp-support-desk-1'

사용량

Company 호출은 측정하거나 과금하지 않으며, Company 자체는 추론을 실행하지 않습니다. 계약 2 예산이 있으면 …/usage에서 한도 상태, 그리고 비용 보고를 기다리는 턴과 비용을 모르는 턴의 수를 볼 수 있습니다. 금액은 나오지 않습니다. 고객 가격 기준의 Company 예산은 결제에서 확인하세요. 예산이 없으면 사용량을 읽을 수 없습니다.

실행 가능한 예제

apps/roye-api-examples/src/company-workspace/는 계약 1 흐름을 생성부터 삭제까지 추론 없이 실행합니다. apps/roye-company-example은 앱에 둔 launch-team 템플릿으로 소유자 승인을 받아 회사를 시작하고, 브리프와 수락 기록을 직접 보관합니다. 실행 방법은 examples/README.md에 있습니다.